AngularJS中的ng-controller是什么東東


 

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM