在其他控制器中的另一个$ http调用之后执行$ http调用

时间:2015-03-17 18:53:26

标签: angularjs angularjs-scope

如何在$http.get控制器中的Portraits完成后调用$http.get控制器中的Match?我需要idMatch来呼叫其他人。

var app = angular.module('Rugby', ['ui.bootstrap']);

var idMatch = 0;

app.controller('Match', ['$http', '$log', function ($http, $log) {
    var $scope = this;

    $http.get('./lib/data.php?query=getMatches').success(function (response) {
        var lastMatch = response.length - 1;
        idMatch = response[lastMatch].idMatch;
        $scope.date = response[lastMatch].date;
        $scope.local = response[lastMatch].local;
        $scope.visitor = response[lastMatch].visitor;
    });

}]);

app.controller('Portraits', ['$http', '$log', function ($http, $log) {
    var $scope = this;
    this.players = [];

    //I need to have the idMatch before this two calls starts
    $http.get('./lib/data.php?query=getPlayersInMatch&idMatch=' + idMatch).success(function (response) {
        $scope.players = response;
    });

    $http.get('./lib/data.php?query=getPlayersOutMatch&idMatch=' + idMatch).success(function (response) {
        $scope.notConfirmedPlayers = response;
    });
}]);

我现在浪费了两天,这可能很简单......

更新:我的应用只需从所有匹配中检索数据,获取最后一个数据的数据,并显示在其中播放的团队和日期。之后,它应该检索我们团队中将播放它并显示其图片和名称的所有玩家。

1 个答案:

答案 0 :(得分:0)

在不知道您的应用程序的要求的情况下,我们只能假设您有合理的理由将这两个控制器分开。

如果控制器是兄弟姐妹并且没有范围继承关系,那么您唯一的选择是通过$ rootScope广播事件。然而,这是不好的做法,应该避免。

如果他们有继承关系,孩子会使用$ emit(向上)而不是$ broadcast

请阅读

https://docs.angularjs.org/guide/scope

https://docs.angularjs.org/api/ng/type/ $ rootScope.Scope

了解范围继承。

以下示例(不是我的)http://jsfiddle.net/VxafF/是一个简单易懂的例子。

$http.get('./lib/data.php?query=getMatches').success(function (response) {
    var lastMatch = response.length - 1;
    idMatch = response[lastMatch].idMatch;
    $scope.date = response[lastMatch].date;
    $scope.local = response[lastMatch].local;
    $scope.visitor = response[lastMatch].visitor;

    $rootScope.broadcast('matchIDEvent', {'idMatch': idMatch});
});

您的肖像控制器需要一个新功能:

$rootScope.$on("myEvent",function (event, data) {
    $http.get('./lib/data.php?query=getPlayersInMatch&idMatch=' + data.idMatch).success(function (response) {
        $scope.players = response;
    });

    $http.get('./lib/data.php?query=getPlayersOutMatch&idMatch=' + data.idMatch).success(function (response) {
       $scope.notConfirmedPlayers = response;
    });
});

两个控制器还需要注入rootScope。