作用
- 当
controller
嵌套的时候,主要是为了区别模板中使用的属性到底来源于自身还是继承 - 但是绑定在this上面的属性,必须通过对于controller进行重命名才可以,博客
例子
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="https://cdn.bootcdn.net/ajax/libs/angular.js/1.6.8/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<h1>{{indexName}}</h1>
<div>{{name}}</div>
<section ng-controller="childCtrl">
<div>{{name}}</div>
</section>
</div>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope) {
$scope.indexName = "主页";
$scope.name="父controller的name";
});
app.controller("childCtrl",function($scope){
})
</script>
</body>
</html>
- 效果
对于代码的解释
- 因为当前
controller
中没有相关的name
属性,那么他就会找到父controller
的name
属性 - 但是,当
controller
嵌套过多的时候,我们就很难知道当前的属性会来自于哪个controller
,所以这个时候this
的绑定就排上用场了,可以看下面的一个例子
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="https://cdn.bootcdn.net/ajax/libs/angular.js/1.6.8/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl as parent">
<h1>{{parent.indexName}}</h1>
<div>{{parent.name}}</div>
<section ng-controller="childCtrl">
<div>{{parent.name}}</div>
</section>
</div>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope) {
this.indexName = "主页";
this.name="父controller的name";
});
app.controller("childCtrl",function($scope){
})
</script>
</body>
</html>
- 如果用this进行绑定的话,那么就可以很清楚的看到当前的属性来自于哪个
controller
博客参考