问题
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:
- Do not manipulate your DOM in controller or services(service, factory). You must do that in directive
- Instead of using jQuery selector you can directly get hold of element and manipulate it inside directive
- 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