Created
July 16, 2015 09:18
-
-
Save samny/d26fb1e4f4be9c748e74 to your computer and use it in GitHub Desktop.
Custom input directive with ngModel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
angular | |
.module('app', []) | |
.directive('myThings', function() { | |
return { | |
require: 'ngModel', | |
controllerAs: 'vm', | |
bindToController: true, | |
scope: { | |
options: '=myThings' | |
}, | |
template: '<p ng-repeat="option in vm.options"><label><input type="checkbox" name="selected[]" ng-model="isSelected" ng-init="isSelected = vm.isSelected(option)" ng-change="vm.toggle(option, isSelected)"> Option {{option.id}}</label></p><code>directive.model{{vm.model}} {{vm.isValid}}</code>', | |
controller: function() { | |
this.model = []; | |
this.isSelected = function(option) { | |
var index = this.model.indexOf(option); | |
return index !== -1; | |
} | |
this.toggle = function(option, isSelected) { | |
var index = this.model.indexOf(option); | |
if (index === -1 && isSelected) { | |
this.model.push(option); | |
} else if (!isSelected) { | |
this.model.splice(index, 1); | |
} | |
} | |
}, | |
link: function(scope, el, attrs, ngModel) { | |
ngModel.$validators.required = function(modelValue, viewValue) { | |
var value; | |
if (attrs.required) { | |
value = modelValue || viewValue; | |
return !!value.length; | |
} else { | |
return true; | |
} | |
}; | |
scope.$watchCollection('vm.model', function(value) { | |
ngModel.$setViewValue(value); | |
ngModel.$validate(); | |
}); | |
ngModel.$render = function() { | |
if (!ngModel.$viewValue) { | |
ngModel.$viewValue = []; | |
} | |
scope.vm.model = ngModel.$viewValue; | |
} | |
} | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment