2016-08-20 28 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

我有单独的指令:'