我是角度js的新手,所以请一些人帮帮我.我的模板在这里:
<form ng-model="signup" form-valid>
<input type="text" name="username" ng-model="signup.username">{{signup}}
</form>
Run Code Online (Sandbox Code Playgroud)
我的指示是这样的:
app.directive("formValid",function(){
return {
restrict:"A",
require:"ngModel",
link:function(scope,element,attrs){
scope.$watch(attrs.ngModel,function(newValue){
if(newValue){
console.log(newValue);
}
});
}
}});
Run Code Online (Sandbox Code Playgroud)
当我在文本框中输入一些值时,模型正在改变,因此"$ watch"应该被触发.但是在这里"$ watch"只在我第一次在文本框中输入任何值时被触发一次.谢谢预先.
Ast*_*sta -1
一种解决方案是使用 ngModel,如下例所示。
app.directive("formValid",function(){
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
scope.$watch(function () {
return ngModel.$modelValue;
}, function(newValue) {
console.log(newValue);
});
}
}
});
Run Code Online (Sandbox Code Playgroud)
编辑:最快的解决方案是遵循Blackhole的评论,并通过添加 来将您的手表更新为深度手表true。这是因为您正在查看signup属性,但模型值username是注册的属性。深度监视将用于监视属性。
直接使用ngModel而不是通过attrs,或使用格式化程序或解析器(在我看来,Michaels 的回答中详细介绍了这是一个更好的解决方案)。
| 归档时间: |
|
| 查看次数: |
4341 次 |
| 最近记录: |