2016-11-11 54 views
1

我似乎無法理解這裏發生了什麼。然而,當使用'this'關鍵字時,我的視圖不會在點擊按鈕上更新;如果我使用「範圍」,它會正確更新。我不確定自己的自定義指令中是否有錯誤。使用ControllerAs和自定義指令時,視圖不會更新

//My custom directive 
app['directive']('myCustomDirective',function(){ 

return{ 
    restrict: 'E', 
    templateUrl: 'templates/someTemplate.html', 
    controller: 'mainCtrl', 
    controllerAs: 'ctrl' 
} 

})

//My controller, will not update view on click 
app['controller']('mainCtrl', ['$scope', function (scope) { 

    this['name'] ='Hello'; 

    this['click'] = function(){ 

     this['name'] = ''; 
    } 
}) 

//Portion of HTML from view. 
<input type="text" ng-model="ctrl.name" required/> 
<md-button class="md-primary" ng-click="ctrl.click()">Submit</md-button> 


//However; if I use the scope (like below) it will update the view 
app['controller']('mainCtrl', ['$scope', function (scope) { 
    scope['name'] =''; 

    this['click'] = function(){ 

    scope['name'] = "You entered your name"; 
    } 
}) 

//Will update the update the view on button click. 
<input type="text" ng-model="name" required/> 
<md-button class="md-primary" ng-click="ctrl.click()">Submit</md-button> 
+0

'NG-模型= 「ctrl.name」 你''了controllerAs ctrl'在不工作的例子嗎? @ drivers34 – taguenizy

+0

我不確定'controller:'mainCtrl', controllerAs:'ctrl''對於一個指令是可以的。您應該根據需要使用組件 – qchap

+0

但是,使用「this」關鍵字時,它不起作用;當我綁定到「範圍」時,它沒有問題。 – drivers34

回答

2

你應該關心當您使用關鍵字在JavaScript。因爲這是指當前範圍的情況下,當你在一個函數中使用它不與這個控制器相同。

這就是爲什麼你會看到控制器的所有實例的語法與

var ctrl = this; 

所以開始,如果你設置這個在開始一個變量並使用該變量爲一個別名你會得到你想要的結果...

app['controller']('mainCtrl', ['$scope', function (scope) { 
    var ctrl = this; 

    ctrl.name ='Hello'; 

    ctrl.click= function(){ 
     ctrl.name = ''; 
    } 
}) 
2

如果你想使用this而不是$scope,你必須寫這樣的控制器:

app['controller']('mainCtrl', ['$scope', mainCtrl]); 

function mainCtrl ($scope) { 
    // here is your code 
} 

如果內部控制你的代碼會更加複雜,好的做法是定義var that = this;和兒童使用的水平,而不是thatthis

您還可以使用mainCtrl.yourProperty

+0

@PoyrazYilmaz錯了?爲什麼?它工作正常,我沒有任何問題,這種結構呢。我用'angular.module( '模塊名')控制器( 'ControllerName',[ControllerName]);',它是確定 –

+0

,然後,當然'函數ControllerName(){...};' –

+0

對不起我的錯誤。 ..我錯誤地讀了代碼。這是好... –

相關問題