2016-05-31 150 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