AngularJS load service then call controller and render

后端 未结 6 1418
生来不讨喜
生来不讨喜 2020-12-28 16:29

My problem is that i need a service loaded before the controller get called and the template get rendered. http://jsfiddle.net/g75XQ/2/

Html:

<
6条回答
  •  长发绾君心
    2020-12-28 16:54

    You can use resolve in the .config $routeProvider. If a promise is returned (as it is here), the route won't load until it is resolved or rejected. Also, the return value will be available to injected into the controller (in this case Somert).

    angular.module('somertApp')
      .config(function($routeProvider) {
        $routeProvider
          .when('/home/:userName', {
            /**/
            resolve: {
              Somert: function($q, $location, Somert) {
                var deferred = $q.defer();
                Somert.get(function(somertVal) {
                  if (somertVal) {
                    deferred.resolve(somertVal);
                  } else {
                    deferred.resolve();
                    $location.path('/error/'); //or somehow handle not getting
                  }
                });
                return deferred.promise;
              },
            },
          });
      });
    

提交回复
热议问题