AngularJS中的ng-controller是什么东东

时间:2022-05-16 00:21:08

在AngularJS中,ng-controller是最常用的directive。比如:

var app = angular.module("app",[]);
app.controlle("AppCtrl", function(){
var app = this;
app.people = [
{"firstName":"", "lastName":""},
...
];
}) app.controller("FirstCtrl", function(){
var first = this;
first.message = "i am the first one";
}) app.controller("SecondCtrl", function(){
var second = this;
second.message = "i am the second one";
})

页面部分:

<body ng-controller="AppCtrl as app">
<div ng-controller="FirstCtrl as first">
{{first.message}}
</div>
<div ng-controller="SecondCtrl as second">
{{second.message}}
</div>
</body>

现在模拟一个ng-controller的directive

app.directive("myController", function(){
return {
scope: true,
controller: '@'
}
})

可见,my-controller和ng-controlller工作原理是一样的。

页面部分使用my-controller

<body my-controller="AppCtrl as app">
<div my-controller="FirstCtrl as first">
{{first.message}}
</div>
<div my-controller="SecondCtrl as second">
{{second.message}}
</div>
</body>

所有的页面呈现都不变。

如果我们想让自定义的my-controller替代AngularJS默认的ng-controller,可以使用priority属性:

app.directive("myController", function(){
return {
scope: true,
controller: '@',
priority: 500
}
})

默认的priority字段值是0.