服务器数据的动态路由

时间:2016-08-28 21:10:21

标签: javascript angularjs angular-ui-router state

我有一些动态定义的嵌套路线:

var res = [
  {i:1,title:"title 1"},
  {i:2,title:"title 2"},
  {i:3,title:"title 3"},
  {i:4,title:"title 4"}
];

app.config(function($stateProvider, $urlRouterProvider, $authProvider,$httpProvider) {
    // other routes [...]
    angular.forEach(res, function(d) {
        $stateProvider.state('nested.q' + d.i, {
           url: '/' + d.i,
           template: '{{d.i}} - {{d.title}}'
       });
    });  
});
应该从服务器的ajax中检索

var res,我不知道如何在角度工作流的这一步骤中完成(先前任何服务或控制器加载)。

编辑基于@RadimKöhler回答我试过这段代码,这有什么问题?路线根本没有注册:

var  $stateProviderRef; // is this global var used like you thought??
app.config(function($stateProvider, $urlRouterProvider,$httpProvider,$locationProvider) {

$stateProvider
    .state('about', {
        url: "/about",
        templateUrl: "/partials/about.html"
    })
$urlRouterProvider.deferIntercept();
$locationProvider.html5Mode({enabled: false});
$stateProviderRef = $stateProvider;

$urlRouterProvider.otherwise('/');

});

app.run([ '$rootScope','$http', '$urlRouter',
    function ($rootScope, $http, $urlRouter)
    {
        $http
            .get("/api/remoteStates")
            .success(function(data)
            {
                angular.forEach(data, function (value, key)
                {
                    console.log(value)
                    $stateProviderRef.state(value.name, {
                        url: value.url,
                        template: value.template
                    });
                });
                $urlRouter.sync();
                $urlRouter.listen();
            });
    }]);

/ api / remoteState回复:

[
  {
    "name": "state1",
    "url": "state1",
    "template": "<h1>state1</h1>"
  },
  {
    "name": "state2",
    "url": "state2",
    "template": "<h1>state2</h1>"
  }
]

1 个答案:

答案 0 :(得分:1)

EXTEND:

根据扩展问题,有a working example。 JSON的调整如下:

// api/remoteStates.json
[
  {
    "name": "state1",
    "url": "/state1",
    "template": "<h1>state1</h1>"
  },
  {
    "name": "state2",
    "url": "/state2",
    "template": "<h1>state2</h1>"
  }
]

这几乎没有改变国家注册

// script.js - first part CONFIG phase
app.config(function ($locationProvider, $urlRouterProvider, $stateProvider) {

    $stateProvider
     .state('about', {
        url: "/about",
        templateUrl: "partials/about.html"
    })

    $urlRouterProvider.deferIntercept();
    $urlRouterProvider.otherwise('/about');

    $locationProvider.html5Mode({enabled: false});
    $stateProviderRef = $stateProvider;
});

app.run(['$rootScope', '$state', '$stateParams',
  function ($rootScope, $state, $stateParams) {
    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;
}])

和运行部分

// script.js - RUN phase
app.run([ '$rootScope','$http', '$urlRouter',
    function ($rootScope, $http, $urlRouter)
    {
        $http
            .get("api/remoteStates.json")
            .success(function(data)
            {
                angular.forEach(data, function (value, key)
                {
                    console.log(value)
                    $stateProviderRef.state(value.name, {
                        url: value.url,
                        template: value.template
                    });
                });
                $urlRouter.sync();
                $urlRouter.listen();
            });
    }]);

检查所有here in action

ORIGINAL部分 检查此Q&amp;答:

AngularJS - UI-router - How to configure dynamic views

如此处所述

  

$urlRouterProvider

     

deferIntercept(延迟)

     

禁用(或启用)延迟位置更改拦截。

     

如果您希望自定义同步URL 的行为(例如,如果您希望延迟转换但保持当前   URL),在配置时调用此方法。然后,在运行时,打电话   配置好自己的$urlRouter.listen()事件处理程序后, $locationChangeSuccess

有一个working plunker

我们需要在配置阶段执行 (推迟执行)

app.config(function ($locationProvider, $urlRouterProvider, $stateProvider) {

    // Prevent $urlRouter from automatically intercepting URL changes;
    // this allows you to configure custom behavior in between
    // location changes and route synchronization:
    $urlRouterProvider.deferIntercept();
    $urlRouterProvider.otherwise('/other');

    $locationProvider.html5Mode({enabled: false});
    $stateProviderRef = $stateProvider;
});

然后,我们会在 run 阶段从服务器($ http)获取数据,并在创建新的动态状态后调用 sync < /强>

app.run([ '$rootScope','$http', '$urlRouter',
  function ($rootScope, $http, $urlRouter) 
  {
    $http
      .get("myJson.json")
      .success(function(data)
      {
        angular.forEach(data, function (value, key) 
        { 
          var state = {
            "url": ...
            "parent" :  ...
            "abstract":  ...
            "views": { ... }
          };

          angular.forEach(value.views, function (view) 
          {
            state.views[view.name] = {
              templateUrl : view.templateUrl,
            };
          });

          $stateProviderRef.state(value.name, state);
        });
        // Configures $urlRouter's listener *after* your custom listener            
        $urlRouter.sync();
        $urlRouter.listen();
      });
}]);