来自“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中你有一个控制器:
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.如果我没有在包装div上放置ng-if指令,一切都会正常工作.当您在输入和具有ng-controller(在这种情况下)的元素之间的元素上有一个指令时,会发生这种情况,该控制创建了自己的非隔离范围.许多指令都是这样的:ng-if或ng-repeat.
如果在ng-model中引用对象的属性,它将“查找”父作用域中的对象并找到适当的作用域.
在小提琴上查看:http://jsfiddle.net/VC5WK/
这是由于javascript中的原型继承如何像以前的answears状态一样工作.