在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.