Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get initial value of ngModel in directive

Tags:

angularjs

I have a directive that requires ngModel. The directive modifies the value stored in ngModel (it implements in-place editing of text). Inside my link function I need to get the value of ngModel before it has been changed.

I tried looking at ngModel.$viewValue, and ngModel.$modelValue. They both eventually get the model's contents, but in the beginning of the directive's life-cycle they get the raw unprocessed angular expression such as {{user.name}}. And I cannot find a way to determine when the expression has been processed.

Any ideas?

directive('test', function() {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, element, attrs, ngModel) {

        }
    };
})
like image 635
akonsu Avatar asked May 09 '14 05:05

akonsu


Video Answer


1 Answers

Use the $parse service:

app.directive('test', function($parse) {
  return {
    link: function (scope, element, attrs) {

      var modelGetter = $parse(attrs.ngModel);
      var initialValue = modelGetter(scope);

    }
  };
});

Or:

app.directive('test', function($parse) {
  return {
    compile: function compile(tElement, tAttrs) {

      var modelGetter = $parse(tAttrs.ngModel);

      return function postLink(scope, element) {

        var initialValue = modelGetter(scope);

      };
    }
  };
});

Demo: http://plnkr.co/edit/EfXbjBsbJbxmqrm0gSo0?p=preview

like image 197
tasseKATT Avatar answered Oct 09 '22 10:10

tasseKATT