当前位置: 动力学知识库 > 问答 > 编程问答 >

angularjs - How do I change attributes on directive element's parent

问题描述:

I started with a directive that restricted to be used as an attribute, and when used, it would add ng-mouseover to the element it was applied. It seems to be a trivial task, you just need to $compile it, right? Wrong, it will work only until you decide to have an isolated scope. here's jsbin that explains what I'm talking about

I couldn't solve that problem, anyway.

Now, maybe it's possible to solve this dilemma by making the directive restrict:'E' and transclude whatever is inside of it. Works? Sure. jsbin

But now, I realized that I need to apply those mouse events not to the element itself but to its parent. As in the first case where I struggled to add attributes and keep the content without having scopepocalypse, once again I'm having similar headaches.

Can you guys show me one simple example how to make a directive with isolated scope that adds ng-mouseevent attributes to its parent?

Sometimes I feel stupid for deliberately overcomplicating my own life. Maybe I just need to attach good old event handlers to the parent element right from inside of directive's controller? Yes, seems like an easy fix, but that would be conceptually wrong, and againsts angular's traditions, isn't that right?

网友答案:

The angular way would be to never dynamically attach directives to parents if you're implementing the compile or link functions. The compile and link process is a one way street - meaning parents are compiled before children. Sure you can try to go against traffic, but doing so is difficult, risky, and more trouble than it's worth. By adding directives to a parent, and then trying to recompile it, you'll probably end up recompiling directives multiple times, or worse, introducing a subtle memory leak. It's a difficult road, I'd advise against it. It is not the angular way.

Instead of asking yourself, how do I add directives to my parents, ask yourself, how do I add directives to my children? Child directives can communicate to parent directives through the 'require' property. Usually, this is flexible enough to handle most situations.

To answer your second question, it is perfectly acceptable to hook into JavaScript events within a directive definition (how do you think ng-mouseover was implemented?). If you do, you should do so inside your link function.

分享给朋友:
您可能感兴趣的文章:
随机阅读: