0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.