UI-RouterAngularngRoute不同。它支持普通ngRoute可以执行的所有操作以及许多其他功能。

我正在将Angular应用程序从ngRoute更改为UI-Router。但是我不太想知道如何以编程方式注入(inject)resolve函数-我在Controllerconfig之外使用的代码段。

因此,使用标准AngularngRoute,我可以将resolve promise动态注入(inject)Angular运行块中:

app.run(function ($route) {
  var route = $route.routes['/'];
  route.resolve = route.resolve || {};
  route.resolve.getData = function(myService){return myService.getSomeData();};
});

现在,我如何使用UI-Router以类似的方式注入(inject)解析 promise ?我尝试传递$stateProvider来访问state,但这对我来说是失败的。
angular.module('uiRouterSample').run(
  [          '$rootScope', '$state', '$stateProvider'
    function ($rootScope,   $state, $stateProvider) {

      //$stateProvider would fail

最佳答案

您可以使用resolve在加载下一个状态之前为 Controller 提供数据。要访问已解析的对象,您需要将它们作为依赖项注入(inject)到 Controller 中。

让我们以购物 list 应用程序为例。我们将从定义应用程序模块开始,并将ui.router作为依赖项包括在内:

angular.module('myApp', ['ui.router']);

现在,我们要定义特定于我们应用程序的购物 list 页面的模块。我们将定义一个shoppingList模块,包括该模块的状态,该状态的解析和 Controller 。

购物 list 模块
angular.module('myApp.shoppingList').config(function ($stateProvider) {

    $stateProvider.state('app.shoppingList', {
        url: '/shopping-list',
        templateUrl: 'shopping-list.html',
        controller: 'ShoppingListController',
        resolve: {
            shoppingLists: function (ShoppingListService) {
                return ShoppingListService.getAll();
            }
        }
    });

});

现在,我们可以将已解析的对象作为依赖项注入(inject)到 Controller 中。在上述状态下,我正在将一个对象解析为名称shoppingLists。如果要在 Controller 中使用此对象,则将其作为具有相同名称的依赖项包括在内。

购物 list Controller
angular.module('myApp.shoppingList').controller('ShoppingListController', function ($scope, shoppingLists) {
    $scope.shoppingLists = shoppingLists;
});

有关其他详细信息,请阅读Angular-UI Wiki,其中包括in-depth guide to using resolve

09-25 17:30
查看更多