我已经创建了一个指令,它验证了行和显示错误是某些行有重复值,这里是代码:
app.directive('isUniqueRow', function() {
return {
require: 'ngModel',
scope: {
ngModel: '=',
isUniqueRow: '='
},
link: function(scope, ele, attrs, c) {
var rows = scope.isUniqueRow;
scope.$watch('ngModel', function(v) {
if(!v || v == '') {
c.$setValidity('unique', true);
return;
}
var count = 0;
for(var i=0;i<rows.length;i++) {
if(rows[i].key == v) {
count++;
}
}
c.$setValidity('unique', count < 2);
});
}
}
})
除了一个问题,它的工作正常,请参阅此处的plunkr:https://plnkr.co/edit/IRkgMPRw3Chd7x43Fzdv?p=preview
问题:
我该如何解决?
答案 0 :(得分:2)
只需使用以下代码修改$watch
代码:
scope.$watch('isUniqueRow', function() { // <== Modified line
var v = scope.ngModel; // <== New line
if(!v || v == '') {
c.$setValidity('unique', true);
return;
}
var count = 0;
for(var i=0;i<rows.length;i++) {
if(rows[i].key == v) {
count++;
}
}
c.$setValidity('unique', count < 2);
}, true); // <== Modified line
我们基本上深入观察(最后通过true
)也在列表上。因此,每当我们从该列表中删除/添加/更新任何项目(rows
)时,我们都会再次验证这些值。
请参阅下面的工作示例
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.objs = [{}];
$scope.add = function() {
$scope.objs.push({});
}
$scope.delete = function(index) {
$scope.objs.splice(index, 1);
}
});
app.directive('isUniqueRow', function() {
return {
require: 'ngModel',
scope: {
ngModel: '=',
isUniqueRow: '='
},
link: function(scope, ele, attrs, c) {
var rows = scope.isUniqueRow;
scope.$watch('isUniqueRow', function() {
var v = scope.ngModel;
if (!v || v == '') {
c.$setValidity('unique', true);
return;
}
var count = 0;
for (var i = 0; i < rows.length; i++) {
if (rows[i].key == v) {
count++;
}
}
c.$setValidity('unique', count < 2);
}, true);
}
}
})
&#13;
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.5.x" src="https://code.angularjs.org/1.5.0/angular.js" data-semver="1.5.0"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<div ng-repeat="row in objs">
<ng-form name="iForm">
<table>
<tr>
<td>
<input name="key" ng-model="row.key" is-unique-row="objs" type="text" />
<div ng-show="iForm.key.$error.unique" style="color: #ff0000;">Must be unique</div>
</td>
<td>
<button ng-click="delete($index)">Del</button>
</td>
</tr>
</table>
</ng-form>
</div>
<button ng-click="add()">Add</button>
</body>
</html>
&#13;