阅读 ng-book 时,有一部分建议在使用 $scope
时,尝试将属性包装在另一个属性中,如下所示:
$scope.model.attribute
而不是 $scope.attribute
根据作者的说法,如果我们有嵌套 Controller ,这将很有帮助,就好像我们不这样做一样,如果我们要更改子 $scope 中的值,它不会上升到父级。
我想我不明白为什么这是必要的? $scope.model.attribute
和 $scope.attribute
在原型(prototype)继承方面有什么区别?
最佳答案
请参阅我为说明此问题而制作的 fiddle 。
http://jsfiddle.net/nicolasmoise/X9KYU/4/
HTML:
<body ng-app="myApp">
<div ng-controller="parentCtrl">
<!--{{message}}<input type="text" ng-model="message">-->
{{obj.message}}<input type="text" ng-model="obj.message">
<div ng-controller="childCtrl">
<!--{{message}}<input type="text" ng-model="message">-->
{{obj.message}}<input type="text" ng-model="obj.message">
</div>
</div>
</body>
Controller :
//Switch between commented/uncommented
angular.module('myApp', [])
.controller('parentCtrl', ['$scope', function($scope){
//$scope.message="Hello";
$scope.obj={message:"Hello"}
}])
.controller('childCtrl', ['$scope', function($scope){
}]);
如果您使用“原语”($scope.message
),从子 Controller 编辑它不会更改父 Controller 中的值。
正如你所说,这一切都与 Javascript 的原型(prototype)继承有关
关于javascript - 为什么建议在 AngularJS 中不要使用 $scope.attribute 而是使用 $scope.model.attribute?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23113202/