在执行另一个之前完成控制器处理

时间:2014-09-10 07:49:46

标签: angularjs controller

我在一个页面中加载了2个控制器:一个由$ routeProvider加载,

的application.js

.when('/service/:serviceId/:serviceName/',
                        {
                            templateUrl : 'view/service/service.html',
                            controller : 'ServiceController'
                        })

另一个在视图中加载

service.html

<div align="left">
        <table class="table-flag">
            <tr ng-controller="LanguageController">
                <td ng-repeat="language in listLanguage"
                    width="50">                 
                    <input type="image" ng-src="img/flags/{{language.code}}.jpg"width="30" height="20"></input> </a>
                </td>
            </tr>
        </table>

        <div>

            <br />
            <ul>
                <table class="table table-hover">
                    <tbody>
                        <tr
                            ng-repeat="detail in service.infoList">                             
                            <td><span ng-bind-html-unsafe="detail.label"></span></td>
                        </tr>
                    </tbody>
                </table>

            </ul>
        </div>

    </div>

我使用rest

从服务器检索一些数据

的ServiceController

Info.controller('ServiceController', function ServiceController(
        $scope, $http, $routeParams, manageDatas) {


    $scope.serviceId = $routeParams.serviceId;
    $scope.serviceName = $routeParams.serviceName ;


    var paramsService = {
        serviceId : $scope.serviceId,
        serviceName : $scope.serviceName 
    };

    $scope.loading = true;

    var response = $http({

        url : 'rest/service',
        params : paramsService,
        method : 'GET'
    });

    response.success(function(service) {
        $scope.service = service;
        $scope.loading = false;
        manageDatas.setArrayData($scope.service.languageList);  // service which allow to pass an array in LanguageController           

    });


});

LanguageController

LanguageController.controller('LanguageController', function ServiceByLanguageController(
        $scope, $http, $routeParams, $timeout , manageDatas , $route) {


    $scope.listLanguage = manageDatas.getDatas(); // retrieve the array passed in ServiceController by a service
   // always null

});

问题是ServiceController中的$ http.success方法总是在语言控制器之后执行(由断点验证),所以数组$ scope.listLanguage总是为空,因为我没有传递数据....

如何在serviceController完成所有处理之后执行languageController?

非常感谢

2 个答案:

答案 0 :(得分:1)

或者,您可以在response.success(function(service){...}中广播事件,比如使用$ rootScope,然后让LanguageController监听此事件,然后执行赋值$ scope.listLanguage = ... < / p>

答案 1 :(得分:0)

简单地说,我会说部分或全部的ServicesController逻辑应该在服务中,而不是控制器。您似乎在manageDatas中有这样的服务。只需将实际加载的所有代码和数据写入服务中的服务即可。