Sharing resources between controllers in Angular.j

2020-03-25 01:13发布

问题:

Simple question.

I have this resource:

var Company = $resource("/company/:_id", {_id: "@_id"}); 

That I want to share between different controllers.

Right now, I am copy-pasting things around but I am still not at the point where I want to add more code and use angular shared services

Any other option ?

回答1:

Just put in a service or factory.

angular.module("myApp", []).
  factory("CompanyResource", function ($resource) {
    return $resource("/company/:_id", {_id: "@_id"}); 
  });

and then you can use it in the controller with

function MapCtrl($scope, $resource, $location, CompanyResource) {
   ...
   CompanyResource.query();
   ...
}

Note that you do not need the $ sign in front of the factory name.