Geraint Anderson Geraint Anderson - 4 months ago 23
AngularJS Question

Update model from Angular directive

I'm trying to update an element from a directive on blur but only the view gets changed, not the model.

app.directive('myDirective', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, ctrl) {
element.bind('blur', function(e) {
element[0].value = 'new val';
});
}
};
});


I've created a simple plunk highlighting the issue:
https://plnkr.co/edit/yicenDSHNagapXxP7yrF?p=preview

Lots of people seem to have this problem and there is lots of advice about how to change a specific model using a function on the scope. But I want to be able to drop this directive onto any input so hardcoding which model to change isn't going to work here.

I've tried using $apply as discussed here but that's not working either.
http://nathanleclaire.com/blog/2014/01/31/banging-your-head-against-an-angularjs-issue-try-this/. What am I missing?

Thanks,

Answer

try this (plunker):

var app = angular.module('myApp', []);
app.controller('myCtrl', ['$scope', function($scope) {

  $scope.myVal = 'Demo';

}]);

    app.directive('myDirective', function() {
      return {
        require: '^ngModel',
        scope:{ngModel:'='},
        link: function(scope, element, attrs, ctrl) {
          element.bind('blur', function(e) {
            scope.ngModel='new val';
            scope.$apply();
          }); 
        }
      };
    });
Comments