AngularJS:如何从$ http获取变量。到另一个控制器?

时间:2016-11-24 13:05:13

标签: angularjs controller angularjs-scope

我一直在使用一个使用WS of moodle来获取信息的angularjs webapp,我对变量有一点问题,我想从$http.得到一个变量,我看到你可以使用服务作为选项或$rootscope,但对我来说还没有成功。

我有两个控制器,我想将$scope.userid传递给 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; 
    })

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

此前的方法是从一个控制器广泛投射事件并在其他控制器上处理事件

在你的userCtrl上广播一个关于rootScope的事件,如下所示

   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;

    });

同样在你的cursostCtrl中获取广播的事件范围如下

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

答案 1 :(得分:2)

您可以在http成功后广播一个事件,如下所示 -

在控制器1中 -

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

在控制器2中 -

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