2
我想讓我的應用程序生成到我的角度模板的路徑,而不是在我的JS文件中對它們的字符串路徑進行硬編碼。目前我有服務器用我需要的所有信息創建一個JSON對象。這裏的渲染HTML的顯示方式:在AngularJS應用程序中動態添加路線
<div ng-cloak ng-controller="BaseCtrl" ng-init="templatePaths = {
"items":[
{"token":"about","template":"http://localhost:32243/ViewTemplate/about.html"},
{"token":"contact","template":"http://localhost:32243/ViewTemplate/contact.html"},
{"token":"home","template":"http://localhost:32243/ViewTemplate/home.html"}
],"defaultTemplate":"http://localhost:32243/ViewTemplate/home.html"
}">
以前我定義我的路線是這樣,但我寧願使用上面,而不是服務器生成的對象。
app.config([
"$routeProvider",
function ($routeProvider) {
$routeProvider
.when("/home", {
templateUrl: "ViewTemplate/home.html"
}).when("/contact", {
templateUrl: "ViewTemplate/contact.html"
}).when("/about", {
templateUrl: "ViewTemplate/about.html"
}).otherwise({
redirectTo: '/home'
});
}
]);
我的問題是,因爲我對我的路線所有的數據現在是$scope.templatePaths
,我不從內app.config
訪問$scope
,我不能找到一種方法,從控制器內添加到路由。我試過this method,但它似乎不再有效。
//Wait until templatePaths is init in the view...
$scope.$watch("templatePaths",() => {
_.each($scope.templatePaths.items, item => {
$route.routes[item.token] = { templateUrl: item.template }
});
});
謝謝,這可能是避免它成爲黑客的最好和最簡單的解決方案! –