AngularJS - 在加载任何控制器之前加载数据

Sn0*_*opr 3 load angularjs single-page-application

我正在制作单页应用程序(SPA).我创建了一个控制器InitialControler,用于从此URL(local.app/init)加载来自服务器的数据.

我希望在任何其他网址之前打开此网址.我正在使用ui-router,我$state.go('init').run()函数中做了一个,但它仍然在页面之前加载了请求的'init'页面

Ser*_*nov 11

首先创建一个叫app的状态

$stateProvider.state('app', {
    abstract:    true,
    templateUrl: "assets/partials/container.html",
    controller:  'AppCtrl',
    resolve: {
        init: function(MyFactory) {
            return MyFactory.resolver();
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

现在,您创建的任何新状态都应该是子app状态.这也很好,因为它成为你的根范围.除非你的工厂解决,否则州不会处理.

这就是您创建工厂的方式

app.factory('MyFactory', function($http){
    var items = [];
    return {
        resolver: function(){
            return $http.get('my/api').success(function(data){
                items = data;
            })
        },
        get() {
            return items;
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

现在处于任何其他状态

$stateProvider.state('app.items', {
    url:    '/items',
    templateUrl: "assets/partials/items.html",
    controller:  function($scope, MyFactory){
        $scope.items = MyFactory.get();
    }
});
Run Code Online (Sandbox Code Playgroud)

更多关于国家的决心

https://github.com/angular-ui/ui-router/wiki#resolve