2014-10-10 56 views
3

我有一个后端生成一个包含有关最重要页面的信息的json文件。我想加载这个json文件,并根据文件中的数据建立相应的状态。我无法将$ stateProvider注入到.run或.controller中,并且我无法将$ http注入到.config中,所以我感觉有点失落。从json文件/ http创建状态

所以问题是。我如何加载json文件,根据这些数据浏览数据并建立状态?

快速编辑:如果我缺乏提供必要的信息,请告诉我,我会尝试改进问题。

回答

4

我试图解决类似的问题,并创建了UI路由器附加“未来的状态”。未来状态会尝试解决其他问题,例如使用RequireJS的延迟加载,整个卸载模块的占位符,以及通过书签URL来路由未加载的占位符。

这里是一个普拉克演示如何使用未来各国你的使用情况:http://plnkr.co/edit/Ny7MQcmy35dKeEjbw57d?p=preview

我尝试使用计算器段亚军,但出了问题,所以这里是代码的非可运行糊。

JS:

// Code goes here 

var app = angular.module("jsonstates", ["ct.ui.router.extras"]); 

app.config([ '$stateProvider', '$futureStateProvider', 
function($sp, $fsp) { 
    var futureStateResolve = function($http) { 
    return $http.get("states.json").then(function(response) { 
     angular.forEach(response.data, function(state) { 
     $sp.state(state); 
     }) 
    }) 
    } 
    $fsp.addResolve(futureStateResolve); 
    console.log($fsp); 
}]); 

app.controller("someCtrl", function() { }) 

HTML:

<!DOCTYPE html> 
<html> 

    <head> 
    <script data-require="[email protected]" data-semver="1.2.25" src="https://code.angularjs.org/1.2.25/angular.js"></script> 
    <script src="https://rawgit.com/angular-ui/ui-router/0.2.11/release/angular-ui-router.js"></script> 
    <script src="https://rawgit.com/christopherthielen/ui-router-extras/0.0.10/release/ct-ui-router-extras.js"></script> 
    <link rel="stylesheet" href="style.css" /> 
    <script src="script.js"></script> 
    </head> 

    <body ng-app="jsonstates"> 
    <h1>Hello Plunker!</h1> 
    <a href="#/top">Top state</a> <a href="#/top/nested">Nested state</a> 
    <div ui-view></div> 
    </body> 

</html> 

JSON:

[ 
    { 
    "name": "top", 
    "url": "/top", 
    "controller": "someCtrl", 
    "template": "<h1>top state</h1><div ui-view></div>" 
    }, 
    { 
    "name": "nested", 
    "parent": "top", 
    "url": "/nested", 
    "controller": "someCtrl", 
    "template": "<h1>nested state</h1><div ui-view></div>" 
    } 
] 
+0

将未来状态之前直接访问的状态时,这项工作已经被加载?示例website.com/nested在您的json中。 – user2215771 2014-10-15 07:27:10

+0

是的,未来状态会延迟UI路由器的路由,直到解决所有的$ fsp.addResolve承诺。 – 2014-10-15 14:13:47

+0

这与我所寻找的非常接近,除非我需要使用templateURL,所以我可以从$ templateCache加载,而不是应用于模板属性的内嵌html标记。还可以使用视图将状态定义为抽象? 任何想法如何我可以做到这一点,使用你已经证明了,感谢您的时间和耐心。我真的需要使用上述条件从json动态加载路由。 – 2014-10-21 14:06:48