How to update ngModel $ modelValue based on updating $ viewValue with user input

Let's say I have the following directive:

myApp.directive('myDirective', function() { return { restrict: 'A', require: 'ngModel', scope: { ngModel: '=' }, link: function(scope, elem, attrs, ngModelCtrl) { scope.$watch('ngModel', function() { ngModelCtrl.$modelValue = 'foo'; }); } } }); 

And the following html:

 <input ng-model="name" my-directive></input> 

Basically, whenever a user changes input, my-directive ideally changes the value of the internal model to "foo", leaving the view value intact.

But when I print $scope.name in the corresponding controller, it does not write "foo", it logs everything that the user entered.

It would seem that ngModelCtrl.$modelValue not what the controller is accessing - am I really getting it wrong?

(Also looking at ngModel in the area is really wrong, but I'm not sure of anything else. Any suggestions would be greatly appreciated!)

+7
angularjs angular-ngmodel angularjs-directive
source share
1 answer

If you are looking for a change in appearance, you should never register a watch. ngModelController $viewChangeListeners specifically designed for this purpose and do not create any additional hours on ngModel. You can also remove the binding of two links to ngModel.

I can think of it.

 .directive('myDirective', function($parse) { return { restrict: 'A', require: 'ngModel', link: function(scope, elem, attrs, ngModelCtrl) { /*Register a viewchange listener*/ ngModelCtrl.$viewChangeListeners.push(function(){ /*Set model value differently based on the viewvalue entered*/ $parse(attrs.ngModel).assign(scope, ngModelCtrl.$viewValue.split(',')); }); } } }); 

Demo

Thinking it the other way around (Credits @Cody), it becomes more concise and appropriate when using $parser .

  ngModelCtrl.$parsers.push(function(val) { return val.split(',') }); 
+9
source share

All Articles