2016-05-31 3 views
0
<custom-input-container> 
     <input ng-model="myModel1" /> 
</custom-input-container> 

<custom-input-container> 
     <select ng-model="myModel2" > 
     </select> 
</custom-input-container> 

内ngModelを見(可能であれば、私はこのディレクティブは「customInput.js」でそれを分離して別のアプリモジュールで使用できるようにしたい)私はこのような何かをしたい、私のディレクティブ

myApp.directive('customInputContainer',function(){ 
    return{ 
     restrict: 'E', 
     priority: 0, 
     link:function(scope,element,attr){ 
      scope.watch->//i want to watch the ngModel of 
      the thing inside <custom-input-container> 
      then do console.log('recipe was updated:'+thenewvalue); 
     } 
    } 
}); 
+0

注:各入力コンテナには入力/選択/テキストエリアのいずれか1つしかありません – anaval

+0

'transclude'とその意味を認識していますか? – AranS

+0

悲しいことに...私は非常にanglejsに新しいです – anaval

答えて

0

ネヴァーマインドは、私はそれが今、この

myApp.directive('customInputContainer',function(){ 
    return{ 
     restrict: 'E', 
     priority: 0, 
     link:function(scope,element,attr){ 
      var modelToWatch = element.find('input','select').attr('ng-model'); 
      scope.$watch(modelToWatch,function(newVal,oldVal){ 
        console.log('recipe updated:'+newVal); 
      }); 
     } 
    } 
}); 

のように働いて得た唯一の問題remaning私customInput.js

を変更することなく、他のプロジェクトへのカスタム入力-コンテナの注射を作成する方法であります
0

要素ディレクティブ内の変数ng-modelを見るには、目的の変数の名前を持つ属性を追加します。

<custom-input-container recipe='myModel1'> 
     <input ng-model="myModel1" /> 
    </custom-input-container> 
    <br /> 
    <custom-input-container recipe='myModel2'> 
     Select 
     <select ng-model="myModel2" 
       ng-options="name for name in [1,2,3]"> 
     </select> 
    </custom-input-container> 

次に、ウォッチャを追加します。

app.directive('customInputContainer',function(){ 
    return{ 
     restrict: 'E', 
     link:function(scope,element,attr){ 
      scope.$watch(attr.recipe, function(value) { 
       console.log('recipe was updated: ', value); 
      }) 
     } 
    } 
}); 

上記のディレクティブは、監視する変数を決定するためにrecipe属性を使用しています。

DEMO on JSFiddle

関連する問題

 関連する問題