Asume we have a directive with a nested directive inside. Both directives want to alter the data before it's being displayed. I used ngModelController to do that but I'm open for other suggestions.
My problem: I can't get it to work without using scope.$apply() but on the other hand scope.$apply() throws an error when I use it what would indicate that it's unnecessary.
Here is a plunkr to the problem: http://embed.plnkr.co/RROBxuITLpYnGkHSQAe3/preview
What am I doing wrong?
I think you should read more about ngModelController
, especially about $formatters
$parsers
and $render
. This is great tutorial: http://www.chroder.com/2014/02/01/using-ngmodelcontroller-with-custom-directives/. They are also explaind in that question: ngModel Formatters and Parsers
In your case you can replace $watch
with formatter function. Formatters are called when value is changed from controller. You can manipulate the data in formatter function and then it will be set as $viewValue
. Good practice is to use as few $watches as possiblle.
Also, imho using:
scope: {
myVal: '=ngModel'
}
Looks bad. It might be confusing for other programmers who will work with your code. ngModel
should be used by placing it in require
property.
I would do it in that way: http://plnkr.co/edit/Ve1Ipm53BiYorjtxron5?p=preview