摘自《ng-book》,它说:
Due to the nature of JavaScript itself and how it passes by value vs. reference, it’s considered a best-practice in Angular to bind references in the views by an attribute on an object, rather than the raw object itself.
.....
In this case, rather than updating the $scope.clock every second, we can update the clock.now property. With this optimization, we can....
我不知道为什么,因为《JavaScript: The Definitive Guide》说:
Is there really any fundamental difference between the variable i and the property i of an object o? The answer is no. Variables in JavaScript are fundamentally the same as object properties.
在本书中:
$scope.time = { now: new Date()}
优于
$socpe.time = new Date();
最佳答案
考虑这个示例 HTML:
<div ng-app>
<div ng-controller="MyController">
<div>{{rawObj}}</div>
<div>{{obj.prop}}</div>
<div ng-if="isShown">
<input ng-model="rawObj" />
<input ng-model="obj.prop" />
<span>{{readOnly}}</span>
</div>
</div>
</div>
在 js 中你有一个 Controller :
function MyController($scope){
$scope.rawObj = "raw value";
$scope.obj = {
prop: "property of object"
}
$scope.readOnly = "read only";
$scope.isShown = true;
}
如果您使用 ng-model="rawObj"开始输入,MyController 中作为 $scope 属性的 rawObj 将不会被修改,但将在 ng-if 的范围内创建一个新属性 rawObj。如果我没有将 ng-if 指令放在包装 div 上,一切都会正常。当您在输入和带有 ng-controller 的元素(在这种情况下)之间的元素上有一个指令时,就会发生这种情况,它会创建自己的非隔离范围。许多指令都这样做,例如:ng-if 或 ng-repeat。
如果您在 ng-model 中引用对象的属性,它将“寻找”父作用域中的对象并找到合适的作用域。
在 fiddle 上查看:http://jsfiddle.net/VC5WK/
这是由于 javascript 中的原型(prototype)继承如何像以前的回答状态一样工作。
关于javascript - AngularJs 为什么更新属性比更新变量更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21903069/