rfcabal
rfcabal

Reputation: 119

AngularJS: How do I get a variable from a $http. to another controller?

I have been working on an angularjs webapp using WS of moodle to get information, I have a little problem with variables, I would like to get a variable from a $http. and I saw that you can use services as an option or $rootscope, but for me have not worked it.

I have two controller and i would like to pass $scope.userid to cursostCtrl

app.controller('userCtrl', function ($scope, $http) {



    field = '&field=username';  
    values = '&values[0]=adminaccap'/*+$scope.username*/;


    url = concatUrl + 'core_user_get_users_by_field' + field + values;


    $http.get(url).then(function (response) {
        $scope.items = response.data;
        $scope.userid = response.data[0].id;
    })

    return  $scope.userid;

});


app.controller('cursostCtrl', function($scope, $http){

    url2 = concatUrl + 'core_enrol_get_users_courses' + '&userid=' + $scope.userid;

    $http.get(url2).then(function (response) {
        $scope.cursos = response.data;
        $scope.nombrecurso = response.data[0].fullname; 
    })

Thanks for your help!

Upvotes: 0

Views: 84

Answers (2)

Avinash Rathod
Avinash Rathod

Reputation: 610

You can broadcast an event after http success like follows -

In controller 1 -

 $http.get(url).then(function (response) {
        // assuming you need response in another controller
        $rootScope.$broadcast('GotResponse',response);
    })

In controller 2 -

$scope.$on('GotResponse', function(event,response){
    // this variable response is what you got from http
    console.log('response--',response);
});

Upvotes: 2

bhanu.cs
bhanu.cs

Reputation: 1365

The way forward here is to broad cast a event from one controller and handle the event on other controller

On your userCtrl broadCast an event to the rootScope as follows

   app.controller('userCtrl', function ($rootScope,$scope, $http) {

        field = '&field=username';  
        values = '&values[0]=adminaccap'/*+$scope.username*/;
        url = concatUrl + 'core_user_get_users_by_field' + field + values;

        $http.get(url).then(function (response) {
            $scope.items = response.data;
            $scope.userid = response.data[0].id;
            $rootScope.$broadcast("myBroadCastedEvent",{myUser:$scope.userid});
        })

        return  $scope.userid;

    });

Also in your cursostCtrl get the broadcasted event scope in as follows

app.controller('cursostCtrl', function($scope, $http){
  $scope.$on("myBroadCastedEvent", function (event, args) {
               $scope.userid = args.myUser;
           })

    url2 = concatUrl + 'core_enrol_get_users_courses' + '&userid=' + $scope.userid;

    $http.get(url2).then(function (response) {
        $scope.cursos = response.data;
        $scope.nombrecurso = response.data[0].fullname; 
    })

Upvotes: 2

Related Questions