Angular.js嵌套的Controller $ scopes必须预定义吗?

时间:2013-08-07 03:41:04

标签: angularjs

为什么要为子控制器的$ scope属性定义一个属性?

HTML元素的ng-class有效:

app.controller("mainController",['$anchorScroll','$scope','$location',function($anchorScroll,$scope,$location){
$scope.forms={};
}]);

app.controller("modalController",['$scope',function($scope){
  $scope.forms.contactForm = false;
  $scope.forms.toggleContactForm = function(){
        $scope.forms.contactForm = !$scope.forms.contactForm;
  }
}]);

<body ng-controller="mainController">
   <div ng-class="{hidden:!forms.contactForm}" id="contactForm" ng-controller="modalController"></div>
</body>

此ng-class不会:

app.controller("mainController",['$anchorScroll','$scope','$location',function($anchorScroll,$scope,$location){
}]);

app.controller("modalController",['$scope',function($scope){
  $scope.contactForm = false;
  $scope.toggleContactForm = function(){
        $scope.contactForm = !$scope.contactForm;
  }
}]);

<body ng-controller="mainController">
    <div ng-class="{hidden:!contactForm}" id="contactForm" ng-controller="modalController"></div>
</body>

1 个答案:

答案 0 :(得分:4)

因为在第一种情况下,您通过引用值访问$scope.forms(两个控制器指向内存中的相同值),在第二种情况下,您只需在子控制器中创建一个布尔基元,在这种情况下父母完全没有意识到它(反之亦然)。