AngularJS factory placement

[亡魂溺海] 提交于 2019-12-12 02:07:00

问题


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();
             }
   }
});

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>

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).

This translates to:

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>

Versus:

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>

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.


回答1:


  1. Do not manipulate your DOM in controller or services(service, factory). You must do that in directive
  2. Instead of using jQuery selector you can directly get hold of element and manipulate it inside directive
  3. Using angular animations instead of relying on jQuery

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

Cheers!!!!



来源:https://stackoverflow.com/questions/25952387/angularjs-factory-placement

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