1. 程式人生 > >Angular(一):Controller中this與$scope的區別與聯絡

Angular(一):Controller中this與$scope的區別與聯絡

在瞭解他們的區別之前,首先要理解Controller的初始化過程,對Angular而言,每個Controller都是一個個的建構函式,必須要例項化後才能進行呼叫,所以,Controller在呼叫時,已經以new的方式執行過一次(請注意,是以new的方式,並不是直接呼叫),所以必定會生成一個Controller例項,而且每一個Controller都是不同的例項,絕不會相互干擾,從而此例項也必然會繼承建構函式中this繫結的所有屬性與方法,請看下面的例子:

<!-- 必須要以as的方式才能獲取到此例項 -->
<div class="container" ng-controller
="AppCtrl as ac">
<h2 ng-click="ac.toggle()">{{ac.username}}</h1> </div> <script> // 完全可以不使用$scope app.controller('AppCtrl', function() { this.username = 'yiifaa'; this.toggle = function () { if(this.username == 'yiifaa') { this
.username = 'yiifee' } else { this.username = 'yiifaa' } } });
</script>

在上面的HTML程式碼中,必須以限定名的方式使用Controller的屬性與方法,為什麼呢?因為它們沒有定義在$scope中啊,就是這麼簡單。

從而,我們可以很容易寫出基於$scope的程式碼,如下:

<div class="container" ng-controller="AppCtrl">
    <h2
ng-click="toggle()">
{{username}}</h1> </div> <script> // 完全可以不使用this,這裡的this是指建構函式的上下文,並非this這個單詞 app.controller('AppCtrl', function($scope) { $scope.username = 'yiifaa'; $scope.toggle = function () { // 因為是方法作用域,這裡的this指向$scope if(this.username == 'yiifaa') { this.username = 'yiifee' } else { this.username = 'yiifaa' } } }); </script>

區別在哪裡?一眼就可以出來,不需要物件的限定名了。

從上面的程式碼可以看出,它們其實沒什麼聯絡,如果非要說有的話,那麼它們都可以在同一個建構函式中互相訪問,$scope是這個函式的形參,this是這個函式的上下文,所以它們絕對不是同一個物件(似乎應該說三遍比較好)。

在this中引用$scope

在第一種方案中引用$scope,因為依賴於HTML定義中Controller的例項名稱,所以靈活性,一般較少使用,如下:

this.toggle = function () {
    //  通過$scope依舊可以獲取此物件
    alert($scope.ac.username)
    if(this.username == '李浩') {
        this.username = '王菲'
    } else {
        this.username = '李浩'
    }
}

在$scope中獲取this

這充分利用了Controller例項的唯一性,將方法定義在scopethisscope的複雜度,從而在HTML中引用時,屬性必須加上例項限定名,這也是官方的示例,程式碼示例如下:

app.controller('AppCtrl', function($scope) {
        var that = this;
        that.username = 'yiifaa';
        $scope.toggle = function () {
            //  因為是方法作用域,這裡的this指向$scope
            if(that.username == 'yiifaa') {
                that.username = 'yiifee'
            } else {
                that.username = 'yiifaa'
            }
        }
});

結論

Controller中的this與$scope都可以儲存域資料資訊,無論哪種方案都可以輕鬆解決域資料與檢視的關聯性問題,但最好不要域資料分散儲存兩個物件中。