2015-01-05 35 views
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 } 
    }); 
}); 

回答

2

而是在你的模板渲染與NG-INIT角度HTML(其結合於$範圍)的,在服務器處理JavaScript。類似於:

<script> 
var MYAPP = MYAPP || {}; 

MYAPP.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" 
}; 
</script> 

這應顯示在包含您的app.js文件之前。

然後在您的app.js文件,您可以(根據需要或其他地方)使用MYAPP爲常數,並將它注入到你的配置:

//define as constant to be injectable. 
app.constant("MYAPP", MYAPP); 

app.config([ 
    "$routeProvider", "MYAPP", 
    function ($routeProvider, MYAPP) { 
     var templatePaths = MYAPP.templatePaths; 
     var items = templatePaths.items; 
     for (var i = 0; i < items.length; i++) { 
      var item = items[i]; 
      $routeProvider.when("/" + item.token, { 
       templateUrl: item.template 
      }); 
     } 

     $routeProvider.otherwise({ 
      redirectTo: templatePaths.defaultTemplate 
     }); 
    } 
]); 

我已經在我的項目中使用了類似的模式,使由客戶端代碼中可用的服務器設置的變量。

+0

謝謝,這可能是避免它成爲黑客的最好和最簡單的解決方案! –