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

AngularJS - load data before loading any controller

我正在制作单页应用程序 (SPA)。我制作了一个名为 InitialControler 的控制器来从服务器加载数据 url (local.app/init).

我希望这个 url 在任何其他 url 之前打开。我正在使用 ui-router,我在 .run() 函数中做了一个 $state.go('init') 但它仍然在 'init' 页面

之前加载请求的页面

一种方法是,在配置中仅声明 'init' 状态。而在InitialController中,加载数据后(服务调用的解析函数),配置其他状态。但是在这种方法中,每当您刷新页面时,url 将变为 local.app.init。

为了即使在重新加载后也能保持该特定状态,我找到的解决方案是有一个启动应用程序,我在其中加载了所需的数据,然后我通过 angular.bootstrap 手动引导主应用程序。

首先创建名为 app 的状态

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

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

这就是您创建工厂的方式

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

现在处于任何其他状态

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

更多关于国家决议

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

如果您使用的是 ui-router,那么您可以使用嵌套状态来解决这个问题。例如:

$stateProvider
    .state("main", {
        url: "/",
        template: '<div ui-view></div>',
        controller: 'InitController'
    })
    .state("main.landing", {
        url: "landing",
        templateUrl: "modules/home/views/landing.html",
        controller: 'LandingPageController'
    })
    .state("main.profile", {
        url: "profile",
        templateUrl: "modules/home/views/profile.html",
        controller: 'ProfileController'
    });

在此示例中,您定义了 3 条路线:“/”、“/landing”、“/profile”

因此,InitController(与“/”路由相关)总是被调用,即使用户直接在 /landing 或 /profile 中输入

重要提示:不要忘记包含 <div ui-view></div> 以在此部分启用子状态控制器加载