2016-08-20 7 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>要素の値がcurrentFormngModelに変更されています。しかし、オプションを選択しても、watch関数は機能しません。何か不足していますか?

答えて

0

$watchをに同じ方法で使用することはできません。angular controllerと同じです。代わりに、このような何かのように変更します。

が変化する。このような何かにあなたのhtml select要素は:

<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?


EDIT:あなたのケースでは、コードが<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) { 
... 

EDIT 3

この更新plunker参照:だから

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

+0

を、私は見ることができません'$ scope'の変更は...? –

+0

できます。私が言っているのは、コントローラで使うのと同じ方法で '$ watch 'を使うことができないということです。 –

+0

私は別々の指示文を持っています: '