时间:2020-12-23 12:20:57 | 栏目:AngularJS | 点击:次
ng-controller是为应用变量添加控制器
当有两个控制器father、child且child 在 father内,那child 可以称为子控制器,它将继承父控制器father的scope。child就可以访问到father的scope中的所有函数和变量。
例:
<div ng-controller="father"> <div >name1:{{ name1 }}</div> <div ng-controller="child">name2:{{ name2 }}</div> </div>
情况1:
app.controller("father",function ($scope) { $scope.name1 = "x"; $scope.name2 = "y"; });
页面显示结果:
name1:x name2:y
情况2:
app.controller("child",function ($scope) { $scope.name1 = "a"; $scope.name2 = "b"; });
页面显示结果:
name1: name2:b:
情况3:
app.controller("father",function ($scope) { if($scope.name1){ $scope.name1 += "!"; console.log($scope.name1); } else { $scope.name1 = "@"; console.log($scope.name1); } if($scope.name2){ $scope.name2 += "#"; console.log($scope.name2); } else { $scope.name2 = "$"; console.log($scope.name2); } console.log("father"); }); app.controller("child",function ($scope) { if($scope.name1){ $scope.name1 += "%"; console.log($scope.name1); } else { $scope.name1 = "^"; console.log($scope.name1); } if($scope.name2){ $scope.name2 += "&"; console.log($scope.name2); } else { $scope.name2 = "*"; console.log($scope.name2); } console.log("child"); });
控制台打印结果:
@ $ father @% $& child
页面显示结果:
name1:@ name2:$&
可以看出name1的页面显示结果与控制台打印结果不一致
结论:
父级控制器先执行而子级控制器后执行。父级和子级控制器都可对父级下scope作用域进行访问操作,但当子级控制器尝试处理父级作用域内、子级作用域外的数据则可能会导致父级中的数据变脏。