Chris White
Chris White

Reputation: 30089

Watching the value of function in an AngularJS directive

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

Upvotes: 9

Views: 5975

Answers (2)

Dan
Dan

Reputation: 63059

Try 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').

Upvotes: 10

user769096
user769096

Reputation:

i would also prefer doing something like that:

scope.$watch(function () {
  return scope.editable();
}, function (val) {
   // ...
});

Upvotes: 8

Related Questions