[英]watch function inside directive is not firing
我有一个角度的指令,如下所示:
angular
.module('accountApp')
.directive('matchTo', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
// var attributes = scope.$eval(attrs.matchTo);
ctrl.$validators.matchTo = function(modelValue) {
var attributes = scope.$eval(attrs.matchTo);
if(attributes.unequal == undefined) {
attributes.unequal = false;
}
console.log(modelValue);
console.log(attributes.matchString);
console.log(attributes.unequal);
if(attributes.unequal) {
if(attributes.matchString == undefined || attributes.matchString == null) {
return true;
} else {
return modelValue != attributes.matchString;
}
} else {
if(attributes.matchString == undefined || attributes.matchString == null) {
return false;
} else {
return modelValue == attributes.matchString;
}
}
}
scope.$watch(attrs.matchString, function() {
ctrl.$validate();
console.log('watch fired');
});
}
}
});
这是我的html:
<input type="text" id="name" name="name" class="form-control form-input" ng-model="creditDebit.name"
ng-disabled="isReadOnly" autocomplete="off"
required
ng-required-err-type="requiredCreditDebit" />
<input type="text" id="code" name="code" class="form-control form-input" ng-model="creditDebit.code"
ng-disabled="isReadOnly" autocomplete="off"
required
match-to="{ matchString: creditDebit.name, unequal: true}"
ng-required-err-type="requiredCreditDebitCode"
ng-matchTo-err-type="unMatchNameAndCode" />
仅当重新加载页面时,监视功能才会触发。 但是我希望它会在价值变化时触发。
您可以使用 。
scope.$watch(attrs.matchString, function() {
ctrl.$validate();
console.log('watch fired');
},true);
或立即尝试
element.bind('keypress', function(event) {
if(event.keyCode === 32) {
event.preventDefault();
}
});
不需要监视属性,因为它不是更改的属性,而是matchString
上的matchString
属性。 所以我会这样:
var matchTo = $parse(attrs.matchTo);
scope.$watch(function () {
return matchTo(scope).matchString;
}, function (value) {
console.log(value);
});
有关详情,请参见此插件 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.