【发布时间】: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>
显示预期的标记<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 也不起作用。
【问题讨论】:
-
你能提供你实际使用的代码吗?
-
你如何调用'pageSelectList'指令?
-
您在控制台中看到任何错误吗?除了 OP 中的无效 JSON - 您的代码似乎有效
-
你能提供plunkr吗?和
pageList的样本值? -
只看到控制台中的错误:错误:[$compile:tplrt] 指令“pageSelectList”的模板必须只有一个根元素。 PageSelectList.html,here fixed plunkr 一切正常
标签: javascript angularjs directive