|
| 1 | +'use strict'; |
| 2 | +// oscUnique is a validation directive |
| 3 | +// use: |
| 4 | +// Put it on an input or other DOM node with an ng-model attribute. |
| 5 | +// Pass a list (array, or object) via osc-unique="list" |
| 6 | +// |
| 7 | +// Sets model $valid true||false |
| 8 | +// - model is valid so long as the item is not already in the list |
| 9 | +// |
| 10 | +// Key off $valid to enable/disable/sow/etc other objects |
| 11 | +// |
| 12 | +// Validates that the ng-model is unique in a list of values. |
| 13 | +// ng-model: 'foo' |
| 14 | +// oscUnique: ['foo', 'bar', 'baz'] // false, the string 'foo' is in the list |
| 15 | +// oscUnique: [1,2,4] // true, the string 'foo' is not in the list |
| 16 | +// oscUnique: {foo: true, bar: false} // false, the object has key 'foo' |
| 17 | +// NOTES: |
| 18 | +// - non-array values passed to oscUnqiue will be transformed into an array. |
| 19 | +// - oscUnqiue: 'foo' => [0,1,2] (probably not what you want, so don't pass a string) |
| 20 | +// - objects passed will be converted to a list of object keys. |
| 21 | +// - { foo: false } would still be invalid, because the key exists (value is ignored) |
| 22 | +// - recommended to pass an array |
| 23 | +// |
| 24 | +// Example: |
| 25 | +// - prevent a button from being clickable if the input value has already been used |
| 26 | +// <input ng-model="key" osc-unique="keys" /> |
| 27 | +// <button ng-disabled="form.key.$error.oscUnique" ng-click="submit()">Submit</button> |
| 28 | +// |
| 29 | +angular.module('openshiftConsole') |
| 30 | + .directive('oscUnique', function() { |
| 31 | + return { |
| 32 | + restrict: 'A', |
| 33 | + scope: { |
| 34 | + oscUnique: '=' |
| 35 | + }, |
| 36 | + require: 'ngModel', |
| 37 | + link: function($scope, $elem, $attrs, ctrl) { |
| 38 | + var list = []; |
| 39 | + |
| 40 | + $scope.$watchCollection('oscUnique', function(newVal) { |
| 41 | + list = _.isArray(newVal) ? |
| 42 | + newVal : |
| 43 | + _.keys(newVal); |
| 44 | + }); |
| 45 | + |
| 46 | + ctrl.$parsers.unshift(function(value) { |
| 47 | + // is valid so long as it doesn't already exist |
| 48 | + ctrl.$setValidity('oscUnique', !_.includes(list, value)); |
| 49 | + return value; |
| 50 | + }); |
| 51 | + } |
| 52 | + }; |
| 53 | + }); |
0 commit comments