Reputation: 588
I'm new to AngularJS, so forgive me if this is a noob question. The documentation is pretty terse, so I may have missed something obvious!
I'm considering migrating a bunch of custom in-house code to Angular, and I have to make Angular work with our REST pattern, in which an input looks like this:
foo: {
value: 100,
min: 50,
max: 150
}
Value becomes the value displayed in an input
element, and min and max are (currently) bound to min and max attributes. These are later picked up by a validation function. If value is outside of the min-max range, it is adjusted back into that range.
Anyway, I'm trying to do something like:
<input type="text" ng-model="foo" my-bind />
... and override ngModel
with a directive named myBind
to manage the relationship, so that the value is read and written to foo.value
.
I would then use a custom validator later to handle the min/max attributes.
Can anyone provide an example of how I might achieve such a binding? I've not had much luck making it work so far.
... or maybe my whole approach is stupid? I do have to work with the data structure above though, I can't change that in the near future.
Upvotes: 1
Views: 4173
Reputation: 4880
I am not entirely sure I understand the question, but it seems like you could do this:
<input type="number" ng-model="foo.value" max="foo.max" min="foo.min" />
If you still need a custom directive, you would do something like this to manipulate the ngModel:
angular.module('customControl', []).
directive('contenteditable', function() {
return {
restrict: 'A', // only activate on element attribute
require: '?ngModel', // get a hold of NgModelController
link: function(scope, element, attrs, ngModel) {
if(!ngModel) return; // do nothing if no ng-model
// Specify how UI should be updated
ngModel.$render = function() {
element.html(ngModel.$viewValue || '');
};
// Listen for change events to enable binding
element.bind('blur keyup change', function() {
scope.$apply(read);
});
read(); // initialize
// Write data to the model
function read() {
ngModel.$setViewValue(element.html());
}
}
};
});
From the AngularJS documentation.
Upvotes: 1