<custom-input-container>
<input ng-model="myModel1" />
</custom-input-container>
<custom-input-container>
<select ng-model="myModel2" >
</select>
</custom-input-container>
我想做这样的事情(如果可能的话,我希望通过在'customInput.js'中分离它来使这个指令在另一个app模块上可用)
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 :(得分: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
属性来确定要监视的变量。
答案 1 :(得分: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);
});
}
}
});
现在唯一的问题是如何在不修改customInput.js的情况下使自定义输入容器可注入其他项目