2015-11-04 109 views
0

我正在嘗試使用某些分層數據來構建應該是一個非常簡單的自定義指令。列表中的每個頁面都有子頁面,數據格式如下:ng-repeat內部自定義角度指令不工作

{"Title 1": "Page Title", "Id": "1", "Pages": {"Title 1.1": "Page Title 1.1", "Id": "2"}, {"Title 1.2": "Page Title 1.2", "Id": "3"}} 

等等。這裏的數據只是一個簡單的例子 - 數據或檢索方法沒有問題。

我有一個指令控制器設置爲:

app.directive('pageSelectList', function() { 
return { 
    restrict: 'EA', 
    replace: true, 
    scope: { 
     pageList: '=' 
    }, 
    templateUrl: '/Scripts/App/Directives/Templates/PageSelectList.html', 
    link: function (scope, elem, attrs) { } 
    }; 
}); 

模板是:

<ul class="page-list page-root"> 
    <li ng-repeat="p in pageList.Pages">{{ p.Title }}</li> 
</ul> 

該指令與從父範圍($scope.listOfPages)繪製數據使用。

但是,使用它時,什麼都不顯示 - 它是空白的。奇怪的是,與下面的標記替換指令模板時:

<p>{{ pageList.Title }}</p> 

預期標記<p>Title 1</p>所示。

看起來該指令與ng-repeat有某種問題,或者重複中使用的數據是pageList對象的子對象。

此外,當指令的標記僅用於具有來自父範圍的數據的常規頁面時,根本沒有問題。這似乎是指令本身的問題。

編輯

這是填充數據的指令頁面控制器:

var pageEditController = function ($scope, $rootScope, $state, $stateParams, pageService) { 
$scope.page = {}; 
$scope.errorMessage = ""; 

getPage(); // This is for other data on the page and not directly linked to directive issue. 

getPages(); // This is to get the directive data 

function getPage() { // Just an http get method for $scope.page }} 

function getPages() { 
    pageService.getTree() 
     .success(function (result) { 
      $scope.pageList = result.Result; // This is where the directive data is loaded into scope 
     }) 
     .error(function (error) { 
      $scope.errorMessage = 'Unable to load pages'; 
     }); 
    }; 

}); 

而且奇怪的現象:

這個模板:

<p>{{ pageList.Title }}</p>

顯示標題OK。

此:

<p>{{ pageList.Title }}</p><p>{{ pageList.Id }}</p>

顯示什麼都沒有。原始示例中的ng-repeat顯然不起作用。

+2

你能提供你實際使用的代碼嗎? – Nhor

+1

你如何調用'pageSelectList'指令? – SaiGiridhar

+0

你在控制檯中看到任何錯誤嗎?除了在OP中無效的JSON - 你的代碼似乎工作 – Grundy

回答

0

正如我們在評論中檢測到的:您的代碼工作正常,並且存在指示模板問題。

當您使用replace:true在你的指令,您加載模板必須有一個根元素否則你會得到一個錯誤:

Error: [$compile:tplrt] Template for directive 'pageSelectList' must have exactly one root element. PageSelectList.html
https://docs.angularjs.org/error/ $compile/tplrt?p0=pageSelectList&p1=PageSelectList.html

所以,解決有兩種方式:

1)包裝你的模板中的容器,就像一個div

<div> 
    your directive 
    <p>{{ pageList.Title }}</p><p>{{ pageList.Id }}</p> 
</div> 

2)刪除標誌replace,或使用它replace: false

1

在該指令中,您提到了「pageList」。但在模板中,您正在使用「PageList」訪問它。所以,我想這可能會解決使用問題。

+0

只是一個錯字 - 已經更新OP – Graham