Is there a way to watch the value of a function expression change in an AngularJS directive? I have the following HTML and JavaScript, and the interpolation of {{editable()}}
in the template shows the value evaluates to true, while inspecting the HTML element in Chrome shows that contenteditable
is false.
Any suggestions on how I can watch the value of this function change, and update the element attr accordingly? Or is there a better way to achieve this? (I'd still like to evaluate the function.)
HTML:
<h4 editable="account.hasRole('ROLE_ADMIN')" content="doc.heading"></h4>
Javascript:
mod
.directive(
'editable',
function() {
return {
restrict : 'A',
template : '<button class="btn pull-right"><i class="icon-pencil"></i></button>{{content}} ({{editable()}})',
scope : {
'content' : '=',
'editable' : '&'
},
link : function(scope, element, attrs) {
scope.$watch('editable', function(newValue) {
element.attr('contenteditable', newValue());
});
}
};
});
Is there a way to watch the value of a function expression change in an AngularJS directive? I have the following HTML and JavaScript, and the interpolation of {{editable()}}
in the template shows the value evaluates to true, while inspecting the HTML element in Chrome shows that contenteditable
is false.
Any suggestions on how I can watch the value of this function change, and update the element attr accordingly? Or is there a better way to achieve this? (I'd still like to evaluate the function.)
HTML:
<h4 editable="account.hasRole('ROLE_ADMIN')" content="doc.heading"></h4>
Javascript:
mod
.directive(
'editable',
function() {
return {
restrict : 'A',
template : '<button class="btn pull-right"><i class="icon-pencil"></i></button>{{content}} ({{editable()}})',
scope : {
'content' : '=',
'editable' : '&'
},
link : function(scope, element, attrs) {
scope.$watch('editable', function(newValue) {
element.attr('contenteditable', newValue());
});
}
};
});
Share
Improve this question
edited Apr 5, 2020 at 1:51
Dan
63.1k18 gold badges109 silver badges118 bronze badges
asked May 23, 2013 at 2:50
Chris WhiteChris White
30.1k4 gold badges73 silver badges95 bronze badges
2 Answers
Reset to default 10Try placing the watch on 'editable()'
instead of 'editable'
Explanation: The reason this is needed is because '&'
points to a dynamically generated function wrapper for the attribute expression rather than the expression itself. This special wrapper function returns the value of account.hasRole('ROLE_ADMIN')
.
i would also prefer doing something like that:
scope.$watch(function () {
return scope.editable();
}, function (val) {
// ...
});