0

I have the following link function in an AngularJS directive:

 link: function(scope, iElement, iAttrs) {
        scope.$watch('name', function(newVal){
            if(newVal){
                console.log(newVal);  
            }
        }, true);
    }

The full fiddle is located here: http://jsfiddle.net/balteo/K4t7P/55/

I am trying to figure out why the $watch function is not invoked when a user changes the name variable in the textarea.

1 Answer 1

1

You are creating a new scope when you write this on your directive

scope: {
    name: '='
}

Just remove it and all will work well

Fiddle

Explanation

About the scope attribute, in the docs, we read:

If set to {} (object hash), then a new "isolate" scope is created. The 'isolate' scope differs from normal scope in that it does not prototypically inherit from the parent scope. This is useful when creating reusable components, which should not accidentally read or modify data in the parent scope.

= or =attr - set up bi-directional binding between a local scope property and the parent scope property of name defined via the value of the attr attribute. If no attr name is specified then the attribute name is assumed to be the same as the local name.

Note that for two-way data-binding, is expected that you pass your model as attribute.

When you do this (write your model as an attribute) it works like a charm (check this fiddle).

But you are passing your attribute via ng-model. It's already available on the scope of the directive. When you create a new scope, you are actually creating a child scope at your controllers scope and setting it to your scope parameter in the link function. In fact, if you watch the $scope.$parent.name it will work as well (check this fiddle).

Sign up to request clarification or add additional context in comments.

8 Comments

I does work indeed. Can you please briefly explain what is going on in the directive link function and what is wrong with the new scope?
I mean to say: why is my new scope not used by the link function?
the new scope is used in link function, but when the directive uses isolated scope, it is no longer binded to the scope which you use in the controller out of the directive
Thanks doodec. Uhmm... I thought that there was a two-way binding with the = operator...
@balteo <input ng-model="name"\> - Bad Idea. <input ng-model="customer.name"\> - Good Idea
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.