javascript - AngularJS Directive or Service? -
my current understanding of angularjs tells me directives should contain dom manipulation , services has logic , info handling.
in case i'm unsure use. got object contains 3 functions:
// creates documentfragment & normal element. // returns fragment. createelem: function(htmlstr) { var frag = document.createdocumentfragment(), temp = document.createelement("div"); temp.innerhtml = htmlstr; while (temp.firstchild) { frag.appendchild(temp.firstchild); } homecoming frag; }, // removes created childnodes. deleteelem: function(htmlstr) { while (htmlstr.firstchild) { htmlstr.removechild(htmlstr.firstchild); } }, // redirects page. opengate: function(keystr) { var open = function() { $location.path("/" + keystr).replace(); $rootscope.$apply(); }; settimeout(open, 500); } i want have access of them through angularjs application.
but i'm not sure whether should create service or directive.
reasons against directive
all of them (okay maybe 2 out of three) aren't directly manipulating or changing dom. create , delete elements, there must applied somewhere else elem.insertbefore( createelem("<div></div>") ); in controller. opengate(); function changes location , has absolutely nil dom.
reasons against service
i'm not handling data. in createelem(); create documentfragment node without parent. if phone call function, nil happen within of dom until insert somewhere.
maybe should split them directives , services? otherwise remain in same context.
you're right in splitting functions directives , services.
services not logic handling. main purpose of services contain info intended shared amongst other parts of site, such controllers , directives. can think way:
am going manipulating dom ? utilize directive.
am going sharing info amongst various components of site? utilize service (i.e service, factory, or provider).
javascript angularjs angularjs-directive angularjs-service angularjs-controller
No comments:
Post a Comment