Where to put a helper function in angular directive?

I created a simple directive:

angular.module("foo").directive('bar',function(){ return { ... template: '<div> \ <div ng-hide="param1.length == 0 && param2...">...</div> \ <input ng-show="param1.length == 0 && param2..." .../> \ </div>', scope: { param1: '=', param2: '=' } }; }); 

but there is duplicated complex logic inside the template, so I would like to extract it into a function and just call this function from the template. Where can I put such a function and how to call it? Should I create a dedicated controller?

+5
source share
3 answers

In the communication function:

 return { ..., template: '<div><div ng-hide="foo()">...</div></div>', link: function(scope) { scope.foo = function() { return scope.param1.length == 0 && ...; }; } }; 
+5
source

You use ads to accomplish this in angular. From angular docs ( https://docs.angularjs.org/guide/services )

Angular services are interchangeable objects that are linked together using dependency injection (DI). You can use the services to organize and exchange codes through your application.

0
source

Here is a simple, compact and straightforward method that I use. First add the service in js.

 app.factory('Helpers', [ function() { // Helper service body var o = { Helpers: [] }; // Dummy function with parameter being passed o.getFooBar = function(para) { var valueIneed = para + " " + "World!"; return valueIneed; }; // Other helper functions can be added here ... // And we return the helper object ... return o; }]); 

Then in the controller, enter your helper object and use any available function using the following:

 app.controller('MainCtrl', [ '$scope', 'Helpers', function($scope, Helpers){ $scope.sayIt = Helpers.getFooBar("Hello"); console.log($scope.sayIt); }]); 
0
source

Source: https://habr.com/ru/post/1202891/


All Articles