【问题标题】:ng-repeat inside Custom Angular Directive Not Working自定义角度指令中的 ng-repeat 不起作用
【发布时间】:2015-11-05 00:27:37
【问题描述】:

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

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

显示预期的标记&lt;p&gt;Title 1&lt;/p&gt;

该指令似乎与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';
        });
     };

});

更奇怪的行为:

一个带有这个的模板:

&lt;p&gt;{{ pageList.Title }}&lt;/p&gt;

显示标题 OK。

这个:

&lt;p&gt;{{ pageList.Title }}&lt;/p&gt;&lt;p&gt;{{ pageList.Id }}&lt;/p&gt;

什么都不显示。显然,原始示例中的 ng-repeat 也不起作用。

【问题讨论】:

  • 你能提供你实际使用的代码吗?
  • 你如何调用'pageSelectList'指令?
  • 您在控制台中看到任何错误吗?除了 OP 中的无效 JSON - 您的代码似乎有效
  • 你能提供plunkr吗?和pageList的样本值?
  • 只看到控制台中的错误:错误:[$compile:tplrt] 指令“pageSelectList”的模板必须只有一个根元素。 PageSelectList.htmlhere fixed plunkr 一切正常

标签: javascript angularjs directive


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    正如我们在评论中发现的那样:您的代码工作正常,但指令模板存在问题。

    当您在指令中使用replace:true 时,您加载的模板必须只有一个根元素,否则会出现下一个错误:

    错误:[$compile:tplrt] 指令“pageSelectList”的模板必须只有一个根元素。 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-06
      • 2023-01-30
      • 1970-01-01
      • 2017-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多