ng-repeat 内部自定义 Angular 指令无效

ng-repeat inside Custom Angular Directive Not Working

我正在尝试使用一些分层数据构建一个应该是非常简单的自定义指令。列表中的每个页面都有子页面,数据的形式为:

{"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>

该指令与从 parent 范围 ($scope.listOfPages) 中提取的数据一起使用。

然而,当使用它时,什么也没有显示——它是空白的。奇怪的是,当用以下标记替换指令模板时:

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

已显示预期的标记 <p>Title 1</p>

指令似乎与 ng-repeat 存在某种问题,或者重复中使用的数据是 pageList [=66] 的子 object =]通过。

此外,当指令的标记仅用于包含来自 parent 范围的数据的常规页面时,根本没有问题。好像是指令本身的问题。

编辑

这是为指令填充数据的页面控制器:

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>

显示标题正常。

这个:

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

什么也没显示。显然 ng-repeat 在原始示例中也不起作用。

在指令中,您提到了 "pageList"。但是在模板中,您正在使用 "PageList" 访问它。所以,我想它可能会解决使用问题。

正如我们在评论中检测到的那样:您的代码工作正常,但指令模板有问题。

当您在指令中使用 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.