質問

In my angular app I have a view, a controller and a service. The service load resources ex:service load persons and initialize value with the result. I want to load my view after my service finish his function to load his resources.

var myApp = angular.module('myApp',[]);

myApp.controller('PersonsCtrl', ($scope, Persons) {
    $scope.persons = Persons.data;
});

myApp.factory('Persons', {
    data: [[function that load resources => take time]]
});

So I want to load my controller when my service finish his initialization. Some ideas?

役に立ちましたか?

解決

Assuming you have a route provider, here's a basic example. When the promise is resolved, "personData" will be injected into your controller. There's not much info about what your service does, so I had to give something very generic.

myApp.config(['$routeProvider', function($routeProvider) {
    $routeProvider
        .when('/persons', {
            controller: 'PersonsCtrl',
            templateUrl: 'persons.html',
            resolve: {
                personData: ['Persons', function(Persons) {
                    return Persons.getData();
                }]
            }
        });
}]);

myApp.controller('PersonsCtrl', ($scope, personData) {
    $scope.persons = personData;
});

myApp.factory('Persons', {
    getData: function() {//function that returns a promise (like from $http or $q)};
});

他のヒント

Maybe try using promises, example below

var myApp = angular.module('myApp',[]);

myApp.controller('PersonsCtrl', ($scope, Persons) {
    $scope.persons = Persons.getData().then(function(response){
        //do whatever you want with response
    });
});

myApp.factory('Persons', function ($http, $q) {
    return {
        getData: function () {
            var def = $q.defer();
            $http.get('url').
                success(function (response) {
                    def.resolve(response);
                })
            return def.promise();
        }
    }
});
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top