Reputation: 2019
i have this very simple directive.
In the code,
i have used '@' for link in the scope. I am able to get it correctly.
But this is not two way binding, so i tried to do it with "=" in scope.
This part does not seems to reflect in my template. I tried to do see if the link variable is present in scope,it seems to be undefined.
Should this directive be placed inside a controller?
What is that i am missing in my code.
Upvotes: 1
Views: 8489
Reputation: 1975
One thing most people forget is that you can't just declare an isolated scope with the object notation and expect parent scope properties to be bound. These bindings only work if attributes have been declared through which the binding 'magic' works. See for more information:
https://umur.io/angularjs-directives-using-isolated-scope-with-attributes/
Upvotes: -1
Reputation: 117370
You seem to be missing the difference between the @
and =
bindings. While the 2 might look similar those are fundamentally different ways of bridging "directive world" with the "page world".
Firstly, let's start with the similarities: both types of binding allows you to pass data from a page that is using a directive to the directive itself (directive intenal scope). But this is where similarities end, and the list of differences goes like this:
=
is the 2-way data binding that can cross page / directive world in both ways: from a page to a directive and from the directive scope to the page scope. @
on the other hand only allows you to pass data from a page to the directive and not from the directive to the page.=
binding allows you pass data defined on scopes - that is - any JavaScript variable (primitives, arrays, objects). @
is different and is passing data through a DOM attribute. As such those attributes are restricted to Strings only.=
and @
are also triggered differently from the page that is using a directive: for =
we need to pass an expression that points to data defined on the scope
while with @
we are going through the DOM and need to use the interpolation directive ({{foo}}
) to access data available on the scope.After all those explanations you can see that using =
in the directive definition we need to pass an expression so if you do this: <mydirective link="link1" group="main"></mydirective>
you are effectively saying: pass to the directive a value of the link1
variable defined on a scope. Since such variable is not defined you are passing undefined
to the directive.
So, if you intend to pass a constant (which I assume you want to do), you will need to write:
<mydirective link="'link1'" group="main"></mydirective>
Here is a working plunk: http://plnkr.co/edit/M3qL4MdmoWjTWzZGkwz0?p=preview
Upvotes: 2