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) {
}
};
})
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With