3

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

Manoj Dhiman
  • 5,096
  • 6
  • 29
  • 68
  • 2
    look at $rootScope.broadcast, or create a service to share the datas – Pierre Emmanuel Lallemant Jan 22 '16 at 11:59
  • 1
    You need a service or factory to share data across controller. See [Angular Service](https://docs.angularjs.org/guide/services) – Max Jan 22 '16 at 12:00
  • 1
    On manage_users controller you must use the $promise try: results.name().then(function(data){$scope.results = data;}); – Max Jan 22 '16 at 12:02
  • You need to create a service, make your `$http` call in that service, collect the data in an object `$scope.results` Then, you can inject the service into any controller and have access to `$scope.results` – frishi Jan 22 '16 at 12:08
  • @PierreEmmanuelLallemant can you please explain how can i do thi s? – Manoj Dhiman Jan 22 '16 at 12:08
  • @ShowStopper: http://stackoverflow.com/questions/24830679/why-do-we-use-rootscope-broadcast-in-angularjs – Pierre Emmanuel Lallemant Jan 22 '16 at 12:17
  • Possible duplicate of [Angular JS / Data Binding / Controller](http://stackoverflow.com/questions/17682168/angular-js-data-binding-controller) – maurycy Jan 22 '16 at 12:20
  • duplicate of http://stackoverflow.com/questions/9293423/can-one-controller-call-another/31469444#31469444 – Shubham Nigam Jan 22 '16 at 12:21
  • Possible duplicate of [Passing data between controllers in Angular JS?](http://stackoverflow.com/questions/20181323/passing-data-between-controllers-in-angular-js) – Shashank Agrawal Jan 22 '16 at 12:37
  • @ShowStopper `$http` request returns a promise object that you have to resolve. I updated my answer with an example that shows how. – frishi Jan 22 '16 at 12:43

6 Answers6

2

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)

1

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
Community
  • 1
  • 1
Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121
0

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.

zamarrowski
  • 483
  • 2
  • 7
0

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);
   })
 }
])
frishi
  • 862
  • 1
  • 10
  • 27
0

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;
  });

});
Spaideri
  • 514
  • 1
  • 5
  • 10
0

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.

SuReSh
  • 1,503
  • 1
  • 22
  • 47