2013-05-13 73 views
5

我是Angular JS的新手,通過研究看起來這是不可能的,但我想仔細檢查/看看是否有一些替代方案會有類似的結果。Angular JS,是否可以動態設置ng-include或ng-controller?

我想要做的是從JSON文件中填充頁面,並使用該JSON文件中的url加載自定義li。所以是這樣的:

JSON /內部控制器:

function ExCtrl($scope) { 

    $scope.examples = [ 
      {name:"example", 
      num: 1, 
      url:"website.html"} 
     ]; 
    } 

JS(內JS)

<ul ng-controller="ExCtrl"> 
    <li ng-repeat="example in examples"> 
     <div ng-include src="folder/{{example.url}}> </div> 
    </li> 
</ul> 

解決方案:

<ul ng-controller="ExCtrl"> 
    <li ng-repeat="example in examples"> 
     <div ng-include src="example.url"> </div> 
    </li> 
</ul> 

它現在是:

function ExCtrl($scope) { 

    $scope.examples = [ 
      {name:"example", 
      num: 1, 
      url:"folder/website.html"} 
     ]; 
    } 

回答

5

從文檔:

ngInclude|src - {string} - 角表達式計算到URL。如果源是字符串常量,請確保將其用引號括起來,例如src="'myPartialTemplate.html'"

在你的情況下,設置一個自定義ngResource是有意義的。在控制器中,注入資源並查詢JSON,然後將JSON分配給作用域變量。

angular.module("foo", "ngResource") 

    .factory("ResourceType", function($resource){ 
    return $resource("/resourcetype/:id", {id: "@id"}, { "update": {method:"PUT"}}); 
    }) 
    .controller("ExCtrl" function($scope, ResourceType){ 
    $scope.examples = ResourceType.query(); 
    }); 

然後,您將在您循環訪問資源時設置ng-include url。

此外,不要{{}}您的變量名稱。

編輯:

我要給你一個Plunker,但它似乎是演戲了。這裏是你想要的內聯源。爲了清楚起見,我刪除了資源片。我想你會想在你決定遠程檢索JSON時將它放回原處。

<!DOCTYPE html> 
<html ng-app="angularjs-starter"> 

    <head lang="en"> 
    <meta charset="utf-8"> 
    <title>Custom Plunker</title> 
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script> 
    <script src="app.js"></script> 
    </head> 

    <body ng-controller="MainCtrl"> 
    <ul ng-controller="MainCtrl"> 
     <li ng-repeat="example in examples"> 
     If {{example.url}} were valid, it would load in the div. 
     <div ng-include="example.url"> </div> 
     </li> 
    </ul> 
    </body> 
</html> 

var app = angular.module('angularjs-starter', []); 

app.controller('MainCtrl', function($scope) { 
    $scope.examples = [ 
    {name:"example", 
     num: 1, 
     url:"example.html"} 
    ]; 
}); 

編輯:普拉克

http://beta.plnkr.co/edit/JNhqoJoykWKf4iqV0ieJ?p=preview

+0

我很抱歉,我很新的這一點,我無法破譯什麼功能的各個部分是做或它的整體目標。 。這是一個從控制器設置url的函數嗎? – Alex 2013-05-13 18:44:22

+0

我更新了我的問題,以更好地反映我目前的系統是什麼,如果有幫助..我能夠得到它現在正確解決我的網址..它會說ng-include src =「example.html」,而不是示例。網址,但它沒有加載它? – Alex 2013-05-13 18:47:06

+0

謝謝,這對我來說容易得多 - 但是,當我簡單地編寫ng-include =「example.url」時,最終結果仍然是ng-include =「example.url」:(它不計算任何東西 – Alex 2013-05-13 19:02:53

相關問題