javascript - 为什么建议在 AngularJS 中不要使用 $scope.attribute 而是使用 $scope.model.attribute?

标签 javascript angularjs prototypal-inheritance

阅读 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/

相关文章:

javascript - 像 React 中的 Bootstrap 模态行为

javascript - 登录详细信息未保存在 localStorage 中

javascript - 带有原型(prototype)的 Object.create()

javascript - 使用 Electron 重载模块时遇到问题

javascript - localStorage - 删除本地|基于键的存储值

javascript - 改变函数的值还是与原型(prototype)保持一致?

javascript - 我无法理解有关 Javascript 继承的一些内容

javascript - .ng-enter 在 Angular 1.3.14 中不起作用?

javascript - AngularJS 我在哪里可以访问已加载 Controller 的范围?

javascript - 为什么Function.prototype不能修改?