Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS AppCtrl wait for HTTP event to success

I'm all new to AngularJS and need some help, I have a "AppCtrl" and from there I have a HTTP webservice call - and need the webservice call response accessible in my other controllers.

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

.controller('AppCtrl', function($scope, $http) {

    $scope.webservice_url = "http://webserviceurl.com/";

    $http.get($scope.webservice_url+"?action=get_settings").success(function(data, status, headers, config) {
        $scope.stations = data.stations;
    });
})

This works FINE - and i can access the $scope.stations in my templates - BUT now i want to access the $scope.stations in my "PlaylistCtrl" controller, but this is undefined :(

.controller('PlaylistCtrl', function($scope, $stateParams) {
    console.log($scope.stations); // is undefined :(
})

How can I make sure the http call is "done" (success) before the "PlaylistCtrl" is loaded ...

like image 690
pkdkk Avatar asked Jun 19 '14 08:06

pkdkk


1 Answers

you should turn the http into service/factory if possible

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, dataService) {
  dataService.then(function (data) {
    $scope.data = data
  })
});


app.controller('SecondCtrl', function($scope, dataService) {
  dataService.then(function (data) {
    $scope.secData = data
  })
});

app.service('dataService', function ($http, $q){
  var defferer = $q.defer()

  $http.jsonp('http://ip.jsontest.com/?callback=JSON_CALLBACK').success(function (data){
    defferer.resolve(data)
  })

  return defferer.promise
})

http://plnkr.co/edit/8k97DngZ8KoFOBPFJG82?p=preview working example

like image 190
maurycy Avatar answered Sep 30 '22 14:09

maurycy