AngularJS: Empty - latest CI build
by mhevery
HTML
<script src="http://ci.angularjs.org/job/angular.js-vojta/239/artifact/build/pkg/1.0.0rc2-0254075d/angular-1.0.0rc2-0254075d.js"></script>
<div ng-app="my">
<form name="myForm" ng-controller="Ctrl" novalidate>
<div ng-repeat="item in items">
<ng:form name=lineForm>
<input ng-model="item.name" type="text" name="name" unique-in="uniqueSet" required >
<span ng-show="lineForm.name.$error.unique">Not unique</span>
<span ng-show="lineForm.name.$error.required">Required</span>
</ng:form>
</div>
<p>I would like the form to be invalid if any pair of these items have the same name.</p>
<button ng-click="add()">Add</button>
<pre>uniqueSet={{uniqueSet|json}}</pre>
</form>
</div>
CSS
input.ng-invalid {
background-color: #FA787E;
}
input.ng-valid {
background-color: #78FA89;
}
JavaScript
function Ctrl($scope) {
$scope.add = function() {
$scope.items.push({name: ""});
};
$scope.items = [{name: 'One'},{name:'Two'}];
$scope.uniqueSet = {};
}
angular.module('my', []).
directive('uniqueIn', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
var set = scope.$eval(attrs.uniqueIn);
ctrl.$formatters.push(validator);
ctrl.$parsers.push(validator);
scope.$watch(
function() {
return set[ctrl.$viewValue] == 1;
},
function(value){
ctrl.$setValidity('unique', value);
}
);
function validator(value) {
console.log(angular.toJson(set), value, ctrl.$modelValue);
var oldValue = value !== ctrl.$modelValue
? ctrl.$modelValue
: (value !== ctrl.$viewValue ? ctrl.$viewValue : value);
if (value !== oldValue) {
if (oldValue) set[oldValue] = (set[oldValue] || 1) - 1;
set[value] = (set[value] || 0) + 1;
}
return value;
}
}
};
});