首页 > Web开发 > 详细

深入理解 AngularJS 的 Scope

时间:2015-10-22 15:49:39      阅读:284      评论:0      收藏:0      [点我收藏+]

一、遇到的问题

问题发生在使用 AngularJS 嵌套 Controller 的时候。因为每个 Controller 都有它对应的 Scope(相当于作用域、控制范围),所以 Controller 的嵌套,也就意味着 Scope 的嵌套。这个时候如果两个 Scope 内都有同名的 Model 会发生什么呢?从子 Scope 怎样更新父 Scope 里的 Model 呢?

<div ng-app="myApp">
    <div ng-controller="ParentController">
        {{parentPrimitive}}
        <br />
        {{parentObj.parentProperty}}
        <div ng-controller="ChildController">

        </div>
    </div>
</div>
var app = angular.module(‘myApp‘,[]);
app.controller(‘ParentController‘,function($scope){
    $scope.parentPrimitive = "some primitive"
    $scope.parentObj = {};
    $scope.parentObj.parentProperty = "some value";
});
app.controller(‘ChildController‘,function($scope){
    $scope.parentPrimitive = "this will NOT modify the parent"
    $scope.parentObj.parentProperty = "this WILL modify the parent";
});

结果:输出:

some primitive 
this WILL modify the parent

深入理解 AngularJS 的 Scope

原文:http://my.oschina.net/u/2395167/blog/520595

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!