AngularJS 工厂放置 [英] AngularJS factory placement
问题描述
我有一个不时弹出的灯箱.有3种方法可以关闭它.关闭按钮,单击它外面的覆盖层和另一种方式.对于接近动作,我决定做一个看起来像这样的工厂:
i have this lightbox that pops up from time to time. There are 3 ways to close it. Close button, clicking the overlay that's outside it and another way. For the close action i decided to do a factory that looks like this:
app.factory('close',function(){
return {
close: function(){
$('.mySelector').fadeOut();
}
}
});
我想要关闭灯箱的 HTML 元素之一是这样的:
One of my HTML elements that i want to have close the lightbox would be something like this:
<a href="" ng-click="close">close lightbox</a>
我面临的问题是:我应该在指令中注入工厂(查看它操作 DOM)还是在控制器中?- 控制器在那里,因为我需要它来做其他事情.第一个的优点是我的标记只会有一个控制器附加到灯箱的顶部元素并完成它.另一方面,指令必须单独附加到每个元素+指令代码本身(可能很少).
The question i am faced with is this: Should i inject the factory in a directive (seeing as it manipulates the DOM) or in a controller? - the controller is there either way since i need it for other stuff. The advantage of the first is that my markup would only have a controller attached to the top element of the lightbox and be done with it. The directive on the other hand will have to be attached to each element individually + there's the directive code itself (little of it may be).
这意味着:
added code for directive +
<top-element-of-lightbox ng-controller="myController"> <!-- controller does NOT have factory injected -->
<a href="" ng-click="close" **my-directive**>close lightbox1</a> <!--directive attached to element -->
<a href="" ng-click="close" **my-directive**>close lightbox2</a> <!--directive attached to element -->
...
</top-element-of-lightbox>
对比:
0(zero) directive code +
<top-element-of-lightbox ng-controller="myController"> <!-- controller HAS factory injected -->
<a href="" ng-click="close">close lightbox1</a> <!-- no directive attachment -->
<a href="" ng-click="close">close lightbox2</a> <!-- no directive attachment -->
...
</top-element-of-lightbox>
最后,我是 Angular 的新手,所以如果你能证明你的回答是合理的,我将不胜感激,也请告诉我我是否以正确的方式处理这整件事,以及是否有我可以改进的地方或其他方法更好的.
Lastly, i am new to Angular so i would appreciate if you justify your response and also please tell me if i am going about this whole thing the right way and if there are areas where i could improve or an other approach would be better.
推荐答案
- 不要在控制器或服务(服务,工厂).你必须在指令中这样做
- 您可以直接获取元素并在指令中操作它,而不是使用 jQuery 选择器
- 使用角度动画而不是依赖 jQuery
最重要的是,您面临的所有疑问和上述问题都在这段精彩的视频中得到了解决,该视频仅解释了如何创建指令以隐藏带有动画的内容.https://egghead.io/lessons/angularjs-animating-the-angular-way
Most importantly all your queries and above issue you face is solved in this awesome video which just explains creating a directive to hide stuff with animations. https://egghead.io/lessons/angularjs-animating-the-angular-way
干杯!!!!
这篇关于AngularJS 工厂放置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!