Sushil Gupta
Sushil Gupta

Reputation: 97

Call service from controller in AngularJS

I am very new to AnjularJs so bear with me. In my current code various controller are using same methods. Methods have been pasted on each controller which is not good practice. But now I want to share those methods between various controller as a CommonUtility.js In order to do that I need to make service or factory that much I got looking online. But not sure how? See below code if you can tell me what to do here. filename: Controller.js

(function(){ 
  var somecontrollers = angular.module('angular'); 
  somecontrollers.controller('NameofController', function ($scope, $http) {
    //code
    ..
    ..
    ..
  });
})();

Filename: CommonUtilities.js

var CommonUtilities = angular.module('CommonUtilities', [])
  .service('Collapse', function () {
    this.CollapseTree = function () {
      var name 
      return name
    }
    method2
    method3
    ...
  });

How do I add reference to commonUtilities.js or its methods in Controller.js? Any help is appreciated. Also one more question. How do I use $scope in CollapseTree function? Thanks.

Upvotes: 0

Views: 1094

Answers (1)

Pop-A-Stash
Pop-A-Stash

Reputation: 6652

Write it like this so it's very clear:

(function(){ 
  'use strict';

  var somecontrollers = angular.module('angular', ['CommonUtilities']); 
  somecontrollers.controller('NameofController', NameofController);

  NameofController.$inject = ['$scope', '$http', 'Collapse'];

  function NameofController($scope, $http, Collapse) {
    Collapse.CollapseTree();
  });
}();

You simply reference it by the name you gave it earlier. Also, be sure to include the module that contains your service.

You cannot use $scope in a service. $scope is strictly for controllers as a way to reference methods and variables in a view.

Upvotes: 1

Related Questions