gpt4 book ai didi

javascript - AngularJS 1.4 迁移 - ngOptions : Has track by broken object equality checks?

转载 作者:搜寻专家 更新时间:2023-10-31 23:24:52 25 4
gpt4 key购买 nike

我希望你们能帮助我阐明自从我们从 Angular 1.3 迁移到 Angular 1.4 以来我一直面临的问题。

我创建了一个支持 JSFiddle演示这个的演示

解释

我有一个包含两个列表的 Controller MyElement实例,用户可以使用 <select> 选择.

还有一个按钮可以比较 ( === ) 所选的 MyElement与列表中的第一个元素。这种比较的结果被记录到控制台。

<select>使用 track by element.id区分MyElement -实例。

看起来奇怪的是,所选项目从不等于列表的第一个元素(即使选择了第一个元素)。绑定(bind)到 ctrl.selectedElement 的对象是不同的对象,但具有相同的属性:

NO!
Object {id: 1, description: "First"}
MyElement {id: 1, description: "First"}

当我删除 track by element.id 回到 Angular 1.3 这种行为消失了(两个元素严格相等,正如我所期望的那样)。

问题

这是一个错误吗?这与fix(ngOptions)有关吗?但我不知何故错过了其中的含义?这是怎么回事?

提前致谢!

最佳答案

当它们引用内存中的相同位置时,JavaScript 中对象的默认相等运算符会产生 true。更新必须以不遵守先前声明的方式更改对象。查看migration docs查看更改是否记录在案。不过,我可以看到 track by 确实在创建一个新对象 - 这将是虚假 === 检查的症结所在


为此使用angular.equals,而不是===。此检查有一些细节,如 angular.equals docs 中所述...

Two objects or values are considered equivalent if at least one of the following is true:

  • Both objects or values pass === comparison.
  • Both objects or values are of the same type and all of their properties are equal by comparing them with angular.equals.
  • Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  • Both values represent the same regular expression (In JavaScript, /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual representation matches).

During a property comparison, properties of function type and properties with names that begin with $ are ignored.

Scope and DOMWindow objects are being compared only by identify (===).

// -- 'YES!'
console.log(angular.equals(this.selectedElement, this.elements[0]) ? 'YES!' : 'NO!');

JSFiddle Link - 更新演示


尝试提供最佳答案的过程中,我在 v1.4.0 中挖掘了 ngOptions 的来源。 ,下面的 track by 代码似乎返回了一个新对象,从而解释了上述所有内容。

// Get the value by which we are going to track the option
// if we have a trackFn then use that (passing scope and locals)
// otherwise just hash the given viewValue
var getTrackByValueFn = trackBy ?
function(value, locals) { return trackByFn(scope, locals); } :
function getHashOfValue(value) { return hashKey(value); };

var getTrackByValue = function(value, key) {
return getTrackByValueFn(value, getLocals(value, key));
};

var locals = {}; // ---------- <<<<<<<<<<<<<<<< ---------- new object
var getLocals = keyName ? function(value, key) {
locals[keyName] = key;
locals[valueName] = value;
return locals;
} : function(value) {
locals[valueName] = value;
return locals;
};

关于javascript - AngularJS 1.4 迁移 - ngOptions : Has track by broken object equality checks?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33039326/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com