Search code examples
angularjscontrollerangularjs-scope

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!


Solution

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