0

Lets say i want to reuse a function in angularjs that returns a specific value but i want to call it in other parts controllers of the app so i don't rewrite it in other places (dry) , where would i put that function in an angularjs app? Would i make a service of factory for this?

Say i have two controllers and in those two controllers i want to call function foo() that returns a certain number when i pass a variable through it. Where would i put function foo() in my angular structure?

john samcock
  • 137
  • 1
  • 8

2 Answers2

0

With Angular 1.x you would need to create a service to make something reusable or like a utility. You can inject this to the controller you want to in a similar fashion as you would do for a http service for example. Taken from the AngularJS website, a service is defined as -

AngularJS services are substitutable objects that are wired together using dependency injection (DI). You can use services to organize and share code across your app.

You can find a very simple servic being implemented here - an example by w3schools

Rajeev Ranjan
  • 3,588
  • 6
  • 28
  • 52
0

AngularJS has three very similar concepts services, factories, and providers. Each one can be used to expose apis using DRY patterns. Most often it's a matter of preference between using a service, factory, or provider. I tend to prefer using factories.

Here is a jsfiddle of a simple example where I use a factory to expose an api: https://jsfiddle.net/kaxtxL1h/

var app = angular
  .module("app", [])
  .factory("myapi", function() {
    var api = {
      foo: function (bar) {
        return bar + "_baz"
      }
    };
    //now api is exposed to whoever injects myapi
    return api;
  })
  .controller("ControllerOne", function($scope, myapi) {
    $scope.value = myapi.foo("one");
  })
  .controller("ControllerTwo", function($scope, myapi) {
    $scope.value = myapi.foo("two");
  });

Here is a good reference for understanding the similarities and differences between services, factories, and providers: AngularJS: Service vs provider vs factory

Steven Wexler
  • 16,589
  • 8
  • 53
  • 80