2016-08-20 29 views
0

我有這樣的指令:

app.directive('selectedForm', function(MainService) { 
    return { 
     scope: { 
      formName: '=currentForm' 
     }, 
     restrict: 'E', 
     link: function($scope, iElm, iAttrs, controller) { 
      $scope.$watch('formName', function(oldV, newV) { 
       console.log(iElm); 
       if (someCondition) { 
        MainService.getForm($scope.formName).then(function(re) { 
         iElm.html(re); 
        }); 
       } 
      }); 
     } 
    }; 
}); 

但是,問題是我不能觀看更改。我在DOM中有一個<select>元素,它改變了currentForm的使用值ngModel。但是,即使我選擇了一個選項,watch函數也不起作用。我錯過了什麼嗎?

回答

0

angular directive中不能使用與angular controller中使用的方法相同的$watch。取而代之的是,將其更改爲這樣的事情:

改變這樣的事情你html選擇元素:

<select model="selectedElements"> 
    ... 
    ... 
</select> 

和你的指令中,改變你的$watch到:

... 
link: function($scope, iElm, iAttrs, controller) { 
      $scope.$watch('iAttrs.model', function(oldV, newV) { 
... 

參見:Is it ok watch the scope inside a custom directive?


編輯:

你的情況的代碼看的<select ng-model='currentForm'> ... </select>值將是:

... 
link: function($scope, iElm, iAttrs, controller) { 
      $scope.$watch('iAttrs.currentForm', function(oldV, newV) { 
... 

EDIT 2

更新爲每評論:

在您的html

<selected-form ng-model="currentForm"></selectedForm> 

,並在控制器

... 
link: function($scope, iElm, iAttrs, controller) { 
      $scope.$watch('iAttrs.ngModel', function(oldV, newV) { 
... 

編輯3

看到此更新plunker:

https://plnkr.co/edit/v5EnmpQ9UtApnM5ErnYi?p=preview

+0

所以,我可以不看改變'$ scope' ...? –

+0

你可以。我只是說,你不能像在控制器中一樣使用'$ watch'。 –

+0

我有單獨的指令:'