2015-11-04 75 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