-
Notifications
You must be signed in to change notification settings - Fork 0
/
ng-distinct-values.js
60 lines (50 loc) · 1.99 KB
/
ng-distinct-values.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
angular.module('ngDistinctValues', []);
angular.module('ngDistinctValues').directive('ngDistinctValues',function ($timeout) {
function setValidityContaining(values) {
var result = _.groupBy(values, function (v) { return v.element.val(); });
for (prop in result) {
if (result[prop].length > 1) {
_.forEach(result[prop], function (item) {
item.ctrl.isValid = false;
item.ctrl.$setValidity('distinct', false);
});
} else {
result[prop][0].ctrl.isValid = true;
result[prop][0].ctrl.$setValidity('distinct', true);
}
}
}
return {
require: 'ngModel',
compile: function (tElem, tAtrrs) {
var values = [];
return function link(scope, elem, atrrs, ctrl) {
// distinct values elements
values.push({ element: elem, ctrl: ctrl });
//////////////////////////////////////////////
// Events
/////////////////////////////////////////////
// new item in ng-repeat
scope.$evalAsync(function () {
setValidityContaining(values);
});
// Remove Item from array (ng-repeat).
scope.$on('$destroy', function (scope) {
var index = scope.targetScope.$index;
values.splice(index, 1);
$timeout(function () {
setValidityContaining(values);
}, 25);
});
// When viewValue or ModelValue change
ctrl.$viewChangeListeners.push(function () {
setValidityContaining(values);
});
// for outside communication
elem.on('input', function () {
setValidityContaining(values);
});
};
}
};
});