Manoj Dhiman
Manoj Dhiman

Reputation: 5166

Can I get Angular variable of one controller in other (variable by $http)

I am new to Angularjs and studied a lot. But I stuck at a point. Google doesn't help me. I have a controller and I have data in $scope.results

app.controller('manage_categories', function($scope, $http, $filter, $window) {
     $scope.results = [];
     $http({
        url: base_url + 'employee/fetchData?table=results',
        method: "POST",
    }).success(function(data) {
        $scope.results = data;
    }); 
})

now i want to access the same in other without any other $http call. I have done with another call but i don't want this . because i need this in many other controllers.something like this

app.controller('manage_users', function($scope, $http, $filter, $window,results) {
     $scope.results = results;
     //~ $http({
        //~ url: base_url + 'employee/fetchData?table=results',
        //~ method: "POST",
    //~ }).success(function(data) {
        //~ $scope.results = data;
    //~ });
})

or any other method. Thanks.

update

I tried this

var myApp = angular.module('myApp',[]);
myApp.factory('results', function() {
  return {
      name : [{id:21,name:'this is test'}]
  };
});

app.controller('manage_users', function($scope, $http, $filter, $window,results) {
         $scope.results = results;
    })

This is working fine . But not working with $http call .

var myApp = angular.module('myApp',[]);
    myApp.factory('results', function($scope,$http) {
       $scope.results=[];
       $http({
            url: base_url + 'employee/fetchData?table=results',
            method: "POST",
        }).success(function(data) {
            $scope.results = data;
        }); 
      return {
          name : results
      };
    });

update 2

after answers i write it like

var canapp = angular.module('canApp', ["ngRoute", "angularFileUpload"]);
canapp.service('ResultsFactory', ['$http', function($http) {
   // http call here
   var url=base_url + 'employee/fetchData?table=results';
   $http.post(url,data).success(function(data){
               this.results = data;
          });

}])

call like this

canapp.controller('get_candidates', function($scope, $http, $filter, $timeout, $window, ResultsFactory) {
$scope.check=ResultsFactory.results;
});

but it is not setting the value in template

Upvotes: 3

Views: 145

Answers (6)

SuReSh
SuReSh

Reputation: 1511

I use this angular code with ionic framework may be its help you..

my factory is..

angular.module('starter.services', [])

    .factory('Chats', function() {
      // Might use a resource here that returns a JSON array

      // Some fake testing data
      var chats = [{
        id: 0,
        name: 'Ben Sparrow',
        lastText: 'You on your way?',
        face: 'img/ben.png'
      }, {
        id: 1,
        name: 'Max Lynx',
        lastText: 'Hey, it\'s me',
        face: 'img/max.png'
      }, {
        id: 2,
        name: 'Adam Bradleyson',
        lastText: 'I should buy a boat',
        face: 'img/adam.jpg'
      }, {
        id: 3,
        name: 'Perry Governor',
        lastText: 'Look at my mukluks!',
        face: 'img/perry.png'
      }, {
        id: 4,
        name: 'Mike Harrington',
        lastText: 'This is wicked good ice cream.',
        face: 'img/mike.png'
      }];

      return {
        all: function() {
          return chats;
        },
        remove: function(chat) {
          chats.splice(chats.indexOf(chat), 1);
        },
        get: function(chatId) {
          for (var i = 0; i < chats.length; i++) {
            if (chats[i].id === parseInt(chatId)) {
              return chats[i];
            }
          }
          return null;
        }
      };
    });

and i use this factory in many controllers

.controller('ChatsCtrl', function($scope, Chats) {
  $scope.chats = Chats.all();
  $scope.remove = function(chat) {
    Chats.remove(chat);
  };
})

.controller('ChatDetailCtrl', function($scope, $stateParams, Chats) {
  $scope.chat = Chats.get($stateParams.chatId);
})

in this code factory hit http:// request only one time and i use response on two controllers. Hope its help you.

Upvotes: 0

vamshi krishna kurella
vamshi krishna kurella

Reputation: 332

Use $broadcast to share the data between controllers. Your code will look like this

app.controller('manage_categories', function($scope, $http, $filter, $window, $rootScope) {
     $scope.results = [];
     $http({
        url: base_url + 'employee/fetchData?table=results',
        method: "POST",
    }).success(function(data) {
        $scope.results = data;
        $rootScope.$broadcast("results",data);
    }); 
});

app.controller('otherCtrlr', function($scope, $rootScope) {
         $rootScope.$on("results", function(event, data){
            $scope.results = data;
         });
    });

But using a service call in the controller is not a best approach. Create a factory and create a method to call your service. From controller you need to call this method. But to avoid two service calls, you definitely need to use broadcast/emit(depending on data transfer is from parent or child)

Upvotes: 2

Spaideri
Spaideri

Reputation: 514

It is strongly recommended to use separated services as frishi pointed out. This sample is in single file and module just to make it readeable. Following implementation stores the promise and actual request is only made on the initial call to getFoo. The rest will get the response from the in memory promise.

'use strict';

angular.module('foo', [])

.factory('FooResource', function SessionResource($http) {

    var fooPromise;

    return {
      getFoo: function getFoo() {
        if(!fooPromise) {
          fooPromise = $http.post('employee/fetchData?table=results');
        }
        return fooPromise;
      }
    };
})

.controller('FooController', function($scope, FooResource) {

  FooResource.getFoo().then(function getFooSuccess(data) {
    $scope.results = data;
  });

});

Upvotes: 0

frishi
frishi

Reputation: 882

Here's a small fiddle explaining how to share data between controllers.

https://jsfiddle.net/frishi/zxnLwz6d/10/

(Check the browser console to see that both controllers can access data via the service.)

Basically the premise of a service is that it is a singleton that can be used by all the controllers registered on your module.

You want to make that $http call in a service:

.service('myService', ['$http', function($http) {

 this.getData = function(){
    // Simple GET request example:
    return $http({
      method: 'GET',
      url: 'https://api.github.com/users/mralexgray/repos' // example API
    }).then(function successCallback(response) {
        return response;
    }, function errorCallback(response) {
       // return error message
    });
    }
 }])

In your controller:

.controller('Controller2',['$scope','myService',function ($scope,myService) {
   $scope.foo = myService.getData();
   //resolve the promise:
   $scope.foo.then(function(data){
     console.log(data);
   })
 }
])

Upvotes: 0

zamarrowski
zamarrowski

Reputation: 483

You can do this:

app.factory('ResultsFactory', resultsFactory);
resultsFactory.$inject = ['$http'];
function resultsFactory = function(){
   var self = {};
   var results = null;

   self.getResults = function(){
       if(!results){
          $http.post(url,data).success(function(data){
              results = data;
          });
       }else{
          return results;
       }
   }

   return self;
}

Only the first time that you call to ResultsFactory.getResults() this executes the $http call.

Upvotes: 0

Shashank Agrawal
Shashank Agrawal

Reputation: 25797

There are various possible way of communicating between two controllers. If you just Google share data between controllers angularjs, you may found various links:

  1. Using Services to Share Data Between Controllers
  2. Sharing Data Between Controllers
  3. Share data between AngularJS controllers
  4. Passing data between controllers in Angular JS?

So, in short, possible ways are:

  1. Using Angular Factories (recommended)
  2. Using $rootScope (not recommended)
  3. Using top most controller's scope as root scope

Upvotes: 1

Related Questions