AngularJS overwrites isolated directive scope

耗尽温柔 提交于 2019-12-04 05:19:05

@ binds the parent scope to the isolated scope and it's a one-way (not one-time) binding. So, any change in the outer scope will reset the value in the directive's isolate scope.

Under the covers, Angular calls attrs.$observe on the element attribute with "@". What this does is that it queues an observer function for the next $digest cycle after the compilation. That observer function is what sets the scope variable every time there is a change in the interpolated value assigned to the attribute.

So, the high-level steps are:

1) for `@` scope variable, set an observer function and queue it for later
2) set `@` scope variable to the interpolated value
3) run the controller, pre- and post-link functions
...
N) observer runs against interpolated value and sets the scope value

So, given this, you can now see why your change didn't persist. It would, if you made it after all of these steps - i.e. with a timeout or in response to an event. And only if the attribute interpolated value hasn't changed.

This is NOT so with "=".

Here's a plunker illustrating the differences.

If you want a one-time passage of variables, just set the scope variable using an attribute in the link function or the controller

scope.myVar = $attrs["my-var"];

and remove myVar from the scope.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!