Dynamic url for $ resource in angular factory without using global variable

How can I define a dynamic factory so that the URL is passed from the controller without using $ rootScope?

  .factory('getData', function ($resource,$rootScope) {
        return $resource($rootScope.url, {id:'@id'}{
            'query': { method: 'GET', isArray: true},
            'get': {
                method: 'GET',
                isArray: true,

                transformResponse: function (data) {
                    data = angular.fromJson(data);
                    return data;
                }
            }
        });
    })

controller

   var data = [];
            $rootScope.url='/userDetails/userId?userId=userID'
            getData.get({id:'123'}).$promise.then(function(data){
            angular.forEach(data,function(dataVal){
             //
            },data)
+4
source share
1 answer

You must create a function in your factory, and then pass the URL and id as parameters to this function when it is called.

For your code, the factory should look something like this:

.factory('getData', function($resource, $rootScope) {
  return {
    query: function(url, id){
      return $resource(url, {userId: id}, {
        'query': {
          method: 'GET',
          isArray:true
        },
        'get': {
          method: 'GET',
          isArray:true,

          transformResponse: function(data) {
            console.log(data);
            data = angular.fromJson(data);
            return data;
          }
        }
      }).get();
    }
  }
})

And then you call it like this getData.query(url,id)in the controller.

+3
source

All Articles