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

10
  • 2
    look at $rootScope.broadcast, or create a service to share the datas Commented Jan 22, 2016 at 11:59
  • 1
    You need a service or factory to share data across controller. See Angular Service Commented Jan 22, 2016 at 12:00
  • 1
    On manage_users controller you must use the $promise try: results.name().then(function(data){$scope.results = data;}); Commented Jan 22, 2016 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 Commented Jan 22, 2016 at 12:08
  • @PierreEmmanuelLallemant can you please explain how can i do thi s? Commented Jan 22, 2016 at 12:08

6 Answers 6

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)

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

6 Comments

$rootScope is not defined :(
include $rootScope in first controller.. wait i will update it!
did this . but not setting the value.
what issue u r facing?
can you share the files and code and what u have done exactly!
|
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

Comments

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.

2 Comments

resultsFactory is undefined.
i did this but it is not setting the value .
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);
   })
 }
])

Comments

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

});

Comments

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.

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.