dchhetri
dchhetri

Reputation: 7136

For custom directive, watch attribute only if expression is passed.

I have a directive that watches a attribute passed in, but for that attribute, a raw string value or a expression can be passed. If a expression is passed then I need to watch it. But if a raw string is passed then I really don't need to watch the attribute. I'm wondering if there is a standard way to optionally watch attribute based on if a expression is passed versus a string? I can check for "{{*}}" in the attrs but not sure if that's complete.

The directive simply does this:

//my-drct.js
 scope.watch( function(){attrs.specialProperty;} , function(value){ 
   controller.update(value); 
 })

and my-drct can be used like so:

<div my-drct = '{{foo}}'> //need to watch
//or
<div my-drct = 'foo' >  //dont need to watch

Upvotes: 0

Views: 408

Answers (1)

gkalpak
gkalpak

Reputation: 48212

You can use the $parse service for that.
The parsed expression has a constant property (boolean), which indicates if the expression is made up by constant parts (so it will stay the same forever) or if it has some dynamic parts as well.

E.g.:

.directive('myDrct', function ($parse) {
    return {
        ...
        link: function myDrctPostLink(scope, elem, attrs) {
            var isConstant = $parse(attrs.myDrct).constant;

            if (isConstant) {
                ...
            } else {
                ...
            }
        }
    };
});

See, also, this short demo.

Upvotes: 2

Related Questions