简体   繁体   中英

AngularJS Directive or Service?

My current understanding of AngularJS tells me that Directives should only contain DOM Manipulation and Services everything which has to do with logic and data handling .

In my case I'm unsure which to use. I got an Object which contains three functions:

// Creates a documentFragment & normal element.
// Returns the fragment.
createElem: function(htmlStr) {
    var frag = document.createDocumentFragment(),
    temp = document.createElement("div");

    temp.innerHTML = htmlStr;

    while (temp.firstChild) {
        frag.appendChild(temp.firstChild);
    }

    return frag;
},
// Removes all created childNodes.
deleteElem: function(htmlStr) {
    while (htmlStr.firstChild) {
        htmlStr.removeChild(htmlStr.firstChild);
    }
},
// Redirects to page.
openGate: function(keyStr) {
    var open = function() {
        $location.path("/" + keyStr).replace();
        $rootScope.$apply();
    };

    setTimeout(open, 500);
}

I want to have access to all of them through my AngularJS application.

But I'm not sure whether I should make this a Service or Directive.

Reasons against Directive

All of them (okay maybe two out of three) aren't directly manipulating or changing the DOM. Even that I create and delete Elements, there must applied somewhere else like elem.insertBefore( createElem("<div></div>") ); in a Controller. The openGate(); function simply changes the location and has absolutely nothing to do with the DOM.

Reasons against Service

I'm not really handling any data. In createElem(); I create a documentFragment which is a Node without a parent. So if I call the function, nothing will happen inside of my DOM until I insert it somewhere.


Maybe I should split them up into Directives and Services ? Otherwise they will always stay in the same context.

You're correct in splitting functions up into Directives and Services.

Services are not just for logic handling. The main purpose of services are to contain information that is intended to be shared amongst other parts of your site, such as controllers and directives. So you can think about it this way:

Am I going to be manipulating the DOM ? Use a directive.

Am I going to be sharing this information amongst various components of my site? Use a Service (ie service, factory, or provider).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM