Javascript 对另一个值作出反应的验证指令适用于1.0.x,但不适用于1.2.x
在angular js中,我想创建一个验证器,当指定另一个值时,该验证器将导致ng模型值无效。现在我有了一些适合AngularJS1.1.4的东西,我使用它是因为我使用了一个旧的plunkr,但是当我切换到1.1.5时,它就停止工作了 我肯定我的示波器有问题,但我不确定是什么问题 以下是我的代码: 这是我的HTML:-Javascript 对另一个值作出反应的验证指令适用于1.0.x,但不适用于1.2.x,javascript,angularjs,angularjs-directive,Javascript,Angularjs,Angularjs Directive,在angular js中,我想创建一个验证器,当指定另一个值时,该验证器将导致ng模型值无效。现在我有了一些适合AngularJS1.1.4的东西,我使用它是因为我使用了一个旧的plunkr,但是当我切换到1.1.5时,它就停止工作了 我肯定我的示波器有问题,但我不确定是什么问题 以下是我的代码: 这是我的HTML:- <!DOCTYPE html> <html ng-app="angularjs-starter"> <head lang="en">
<!DOCTYPE html>
<html ng-app="angularjs-starter">
<head lang="en">
<meta charset="utf-8">
<title>Custom Plunker</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.1.3/angular.min.js"></script>
<link rel="stylesheet" href="style.css">
<script>
document.write('<base href="' + document.location + '" />');
</script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<form name="myForm" ng-submit="doSomething()">
<input type="text" name="fruitName" ng-model="data.value" serverError errorValue="data.value.$$error" />
<div>{{ data.value.$$error }}</div>
<span class="invalid" ng-if="myForm.fruitName.$error.serverError">
{{data.value.$$error}}
</span>
<br/>
<button type="submit" ng-disabled="myForm.$invalid">Submit</button>
<input type="button" ng-click="data.toggleError()" value="Toggle Error"/>
</form>
</body>
</html>
一旦我从1.1.3更改为1.2.0,我的指令就停止工作。我已经解决了
该指令非常简单:-
app.directive('serverError', function($parse) {
return {
// restrict to an attribute type.
restrict: 'A',
// element must have ng-model attribute.
require: 'ngModel',
// scope = the parent scope
// elem = the element the directive is on
// attr = a dictionary of attributes on the element
// ctrl = the controller for ngModel.
link: function(scope, elem, attr, ctrl) {
scope.$watch(attr.serverError, function(newValue, oldValue) {
if (newValue != null) {
ctrl.$setValidity('serverError', false);
}
else {
ctrl.$setValidity('serverError', true);
}
});
}
};
});
而不是作用域。$watch'attr.errorValue'使用attr.$observe'errorValue'@HarishR我按照你说的做了,但是它在1.2.x中仍然不起作用。你可以设置一个plunker@HarishR是的。
app.directive('serverError', function($parse) {
return {
// restrict to an attribute type.
restrict: 'A',
// element must have ng-model attribute.
require: 'ngModel',
// scope = the parent scope
// elem = the element the directive is on
// attr = a dictionary of attributes on the element
// ctrl = the controller for ngModel.
link: function(scope, elem, attr, ctrl) {
scope.$watch(attr.serverError, function(newValue, oldValue) {
if (newValue != null) {
ctrl.$setValidity('serverError', false);
}
else {
ctrl.$setValidity('serverError', true);
}
});
}
};
});