2014-09-20 62 views
0

我是Angular的新成員,並且遇到了一些問題。這裏是處理:控制器屬性的更改不會影響視圖

在已經宣佈名爲「myMod」我定義一個指令一個模塊,這樣的方式:

myMod.directive("myDirective", function() { 
    dir = { 
     restrict:'A', 
     template: '<h3>{{myController.name}}</h3> <span class="button">Click to change name</span>', 
     link: function(scope, element, attrs, ctrl) { 
      $(element).find('.button').click(function(){ 
       scope.changeName('John'); // I found this way to call my controller's function 
      }); 
     }, 
     controller: ['$scope', function($scope){ 
      this.name = 'Michael'; 
      var self = this; 

      $scope.changeName = function(newName){ 
       self.name = newName; 
      }; 
     }], 
     controllerAs: 'myController' 
    }; 
    return dir; 
}) 

,我將在我的html這個指令那樣簡單:

<div my-directive></div> 

所以,儘管最初我得到正確的看法(它呈現命名爲「邁克爾」正確),當我按下按鈕,即使控制器的屬性值「名稱」更改爲「約翰」頁面上的名字仍然是「邁克爾」。我究竟做錯了什麼?

在此先感謝

回答

0

編輯我的答案顯示工作小提琴。以下是使用鏈接功能和控制器功能和示波器的示例。

directive("myDirective", function() { 
    dir = { 
     restrict: 'A', 
     template: '<h3>{{myController.name}}</h3> <span class="button" ng-click="callController()">Click to change name</span>', 
     link: function (scope, element, attrs, ctrl) { 

      scope.callController = function() { 
       scope.changeName('John'); 
      } 
     }, 
     controller: ['$scope', function ($scope) { 
      this.name = 'Michael'; 
      var self = this; 

      $scope.changeName = function (newName) { 
       self.name = newName; 
      }; 
     }], 
     controllerAs: 'myController' 
    }; 
    return dir; 
} 

小提琴這裏:

http://jsfiddle.net/nr5c9v1e/1/

+0

好吧,雖然這僅僅是一個例子。我已經在我的指令的鏈接函數上設置了一個上傳庫,並且我正試圖在上傳開始或從庫回調的作用域結束時調用控制器的函數。所以,我當然需要這個電話給控制器。這只是一個簡單的例子,只是爲了陳述我面臨的問題 – 2014-09-20 13:11:40

+0

好的,編輯我的答案。 – sma 2014-09-20 13:34:34