将数据从一个指令传递到另一个指令
问题描述:
我有一个使用自定义模板的指令,我想将数据从该指令传递给另一个指令,并寻找最佳方式.所以,我希望当指令一中的数据发生变化时,指令二得到通知(观察者?),并对其采取行动.到目前为止,只有在指令一中带有控制器的方法,以及控制器方法(来自指令一)的指令二中的观察者才有意义.有没有更好的方法?
I have a directive that uses custom template, and I would like to pass the data from that directive to another one, and looking for the best possible way. So, I would like when the data inside the directive one changes, directive two get notified(watcher?), and acts upon it. So far, only the method with controller inside the directive one, and a watcher inside directive two for the controller method(from directive one) makes sense. Is there a a better way for this ?
-------------- --------------
| directive 1 |---data-->| directive 2 |
| | | |
--------------- --------------
答
您可以使用 $broadcast:
关于第一个指令:
$rootScope.$broadcast("NEW_EVENT", data);
关于另一个指令:
scope.$on("NEW_EVENT", function(event, data){
//use the data
});