Magnum23
Magnum23

Reputation: 417

Common code at one place for different angular directives

I have several different angular directives each showing an icon based on SAME condition and same input, these directives are being used in different htmls views.

Where can i put the logic at one place to get the icon based on that same condition so that each directive does not repeat/have the logic to decide the icon.

Logic can be as follows, each directive has $scope.item property in it.

getIcon(item){

   if(item.name === "A")
   return "iconA";

   if(item.name === "A")
   return "iconB";

   if(item.name === "A")
   return "iconC";

   return "iconHelp";
}

Upvotes: 0

Views: 102

Answers (1)

Dmitri Algazin
Dmitri Algazin

Reputation: 3456

Simple service:

.service("IconUtils", function () {
    return {
        getIcon: function (item) {
            if (item.name === "A")
                return "iconA";

            if (item.name === "B")
                return "iconB";

            if (item.name === "B")
                return "iconC";

            return "iconHelp";
        }
    }
})

Usage in controller:

YourController: function($scope, IconUtils) {

console.log("IconUtils.getIcon()", IconUtils.getIcon({'name' : 'A'}));
console.log("IconUtils.getIcon()", IconUtils.getIcon({'name' : 'B'}));
console.log("IconUtils.getIcon()", IconUtils.getIcon({'name' : 'C'}));
console.log("IconUtils.getIcon()", IconUtils.getIcon({'name' : 'X'}));

}

Upvotes: 1

Related Questions