0

Angular two ways UI binding is great. It is so easy to use because angular handle binding the value automatically. but what if I want to compute the value in between bindings, something like getter and setters to computed the value. How shall I go about it?

I see that we can use filters for getters, but what about setters?? what I want is when a user inputs a number like 10, I need to compute it before setting to the scope model. any ideas?

thanks in advance.

1 Answer 1

1

You could store the unprocessed value to the scope, watch it and compute the derived value:

$scope.userInput = 3;

$scope.watch('userInput', function(newValue) {
   $scope.computedUserInput = newValue + 1;
});

Alternatively, if you are using a default directive that supports ng-change, you could simply use that and call a method in your scope directly.

And a third way would be using ngModelController which I find a bit heavy for some simple cases but provides the transparency you seem to be seeking: http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController

Sign up to request clarification or add additional context in comments.

4 Comments

thank you for the answer, but I think the two approaches your propose above both break the two-way data bindings. isn't that?
In a way, yes. To my knowledge, there is no way to preprocess user input using the simple two way binding notation.
You could always define getters/setters on your scope if you only support > IE8; But I usually stay clear of these in application code.
I think the third option is the right way to do it. thanks for helping finding the solution. much appreciated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.