Get initial ngModel value in directive

I have a directive that requires ngModel. The directive changes the value stored in ngModel(it implements text editing in place). Inside my function, linkI need to get the value ngModelbefore it is changed.

I tried to look ngModel.$viewValueand ngModel.$modelValue. Both of them ultimately get the content of the model, but at the beginning of the directive's life cycle, they get a raw unprocessed angular expression, such as {{user.name}}. And I cannot find a way to determine when the expression is processed.

Any ideas?

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

        }
    };
})
+4
source share
1 answer

Use the service $parse:

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);

      };
    }
  };
});

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

+7

Source: https://habr.com/ru/post/1539860/


All Articles