gpt4 book ai didi

angularjs - ng-repeat 中的表达式如何工作?

转载 作者:行者123 更新时间:2023-12-02 22:40:19 24 4
gpt4 key购买 nike

我正在尝试找出如何使用 ng-repeat 循环遍历对象数组。

我有一个像这样设置的工厂,里面有三组数据:

mainApp.factory("dashboardContent", function() {
return {
contentBoxes: [
{
boxType: "image",
boxIcon: "icons-image",
boxTitle: "on Chapter 1, paragraph 3",
header: {
title: "Lorem ipsum title sit amet",
subtitle: "by Lorem Ipsum"
},
authorImage: "/asssets/ssfsgterwes",
embedContent: ""
},
{
boxType: "audio",
boxIcon: "icons-audio",
boxTitle: "on Chapter 12, paragraph 2",
header: {
title: "lorem ipsum audio sit maet",
subtitle: "by multiple objects"
},
authorImage: "/asssets/ssfsgterwes",
embedContent: ""
},
{
boxType: "quote",
boxIcon: "icons-lightbulb",
boxTitle: "on Chapter 01, paragraph 5",
header: {
title: "lorem ipsum quote sit maet",
subtitle: "by multiple objects parsing"
},
authorImage: "/asssets/ssfsgterwes",
embedContent: ""
}
]
}
})

以及我注入(inject)工厂的指令:

.directive('contentBox', function(dashboardContent) {
return {
restrict: 'E',
scope: {},
replace: true,
templateUrl: '/modules/contentbox.html',
link: function (scope, element) {
scope.contentData = dashboardContent.contentBoxes;
if (!$.isEmptyObject(scope.contentData.header)) {
element.children('.content').prepend(
'<div class="content-header">' +
'<span class="content-title">' +
scope.contentData.header.title +
'</span>' +
' <br/>' +
'</div>'
);
if (!$.isEmptyObject(scope.contentData.header.subtitle)) {
element.find('.content-header').append(
'<span class="content-author">' +
scope.contentData.header.subtitle +
'</span>'
);
}
}
}
}
})

在我看来,我试图像这样循环它:

<content-box ng-repeat="content in contentData"></content-box>

在这种情况下我需要使用什么表达式?我无法理解 ng-repeat文档这个表达式是如何工作的,我发现在“contentData中的内容”中,contentData指的是我的一组对象,但是第一个词是什么(内容,正如我在这里设置的那样),它指的是什么?

另外,我是否正确设置了这个范围?就像上面的代码一样:

scope.contentData = dashboardContent.contentBoxes;

我从中得到的输出是三个空内容框,所以我猜测它正在循环遍历它,但其中没有打印任何数据 - 即 {{contentData.boxTitle}} 仅返回空

在这种情况下我是否正确使用了 ng-repeat ?

最佳答案

您正在将服务 dashboardContent 直接注入(inject)指令中。这不是必需的。您可以将其注入(inject)到 Controller 中,使用 ng-repeat 访问单个数组元素并将其传递给您的指令。

mainApp.controller('ContentCtrl', function($scope, dashboardContent) { 
$scope.contentData = dashboardContent.contentBoxes;
});

在指令代码中替换

scope: {}

scope: { contentData: '='}

并删除行scope.contentData=...

这样,您将拥有一个具有隔离范围的指令,并且您可以在 html 中将值传递给此范围,如下所示:

<div ng-controller="ContentCtrl" ng-repeat="content in contentBoxes">
<content-box contentData="content"></content-box>
</div>

关于angularjs - ng-repeat 中的表达式如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17484888/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com