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

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

我想要做這樣的事情(如果可能的話,我想這個指令通過它在「customInput.js」分離是另一個應用模塊可用)看ngModel我的指令內

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

注意:每個輸入容器只有其中的一個input/select/textarea – anaval

+0

您是否知道'transclude'及其含義? – AranS

+0

可悲的是...我是非常新的angularjs – 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

相關問題