问题发生在使用 AngularJS 嵌套 Controller 的时候。由于每一个 Controller 都有它对应的 Scope(至关于做用域、控制范围),因此 Controller 的嵌套,也就意味着 Scope 的嵌套。这个时候若是两个 Scope 内都有同名的 Model 会发生什么呢?从子 Scope 怎样更新父 Scope 里的 Model 呢?html
<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"; });
结果:输出:app
some primitive
this WILL modify the parentthis
还有另外一种方法:spa
一、在子做用域中使用 $parent.xxx,这样能够直接修改父做用域的属性。code
eg:
orm
$scope.$parent.parentObj = "this WILL modify the parent";