我试图创建一个指令来检查输入到文本框中的值的唯一性。但是newVal和oldVal总是未定义为scope。$ watch包含在ctrl。$ parsers.push()函数中。
有人知道为什么newVal和oldVal未定义?
这里是的jsfiddle:
http://jsfiddle.net/charms/v6ttW/7/
HTML
<div ng-app="myApp" ng-controller="TestCtrl">
{{testVar}}
<form novalidate>
<input type="text" name="user.email" ng-model="user.email" email-used="/api/user"/>
</form>
</div>
Angularjs
angular.module('myApp', [])
.controller('TestCtrl', ['$scope',function($scope) {
$scope.user = {email: 'abc', name: 'myname'};
$scope.testVar = "Test";
}])
.directive('emailUsed', [function() {
return {
require: 'ngModel',
link: function(scope, elem, attr, ctrl) {
console.log("executing");
ctrl.$parsers.push(function() {
ctrl.$setValidity('eaCheckingUniqueValue', true);
if(ctrl.$valid) {
console.log("valid");
scope.oldValues = [];
scope.$watch(attr.ngModel, function(newVal, oldVal) {
scope.oldValues.push(newVal);
console.log("new value is: " + newVal);
});
console.log("valid is true");
} else {
console.log("valid is false");
}
});
你不应该把一个'范围$腕表()解析器的内部'功能,因为它会注册一个新的'$范围的手表。 ()'每次解析器执行时(每次输入改变时)。 – rtcherry
感谢您的投入。这已经有很大帮助了。你有什么建议,我怎么会得到ngModel的价值在我的指令每当价值改变,以便我可以验证它是否已经存在? –