gpt4 book ai didi

javascript - AngularJS 中不同范围的值匹配

转载 作者:行者123 更新时间:2023-12-02 14:51:12 25 4
gpt4 key购买 nike

我试图根据元素的“类别”属性将类应用于元素,同时与用户也可以创建的动态类别列表进行交互。

类别数组:

$scope.categories = [{
category: "work",
id: 1
}, {
category: "life",
id: 2
];

待办事项数组:

$scope.todos = [{
name: "Lift Up Hats",
category: "life",
date: "tomorrow"
}, {
name: "Wash the Horse",
category: "work",
date: "tomorrow"
}];

我实际上想做的是:

A) 循环 todos 数组中的所有内容。到目前为止,这样做是这样的:

<li class="{{todo.category}}-item" ng-repeat="todo in todos | orderBy: 'completed'">

但是,这取决于类被称为“life-item”、“work-item”等。我想使用类别数组中的 ID。

B) 如果“lift up hats”的类别为“life”,则从类别数组中为其分配类别 life 的 ID。例如,生活会导致“1-item”,工作会导致“2-item”等。

我已经研究过使用 .map 函数来实现此目的,但似乎我必须重新构建在整个应用程序中操作数组的方式。

我们将不胜感激一些帮助/建议。

长话短说:我正在尝试将一个类应用于从一个数组循环的 ng-repeated 项,其中该类是另一个数组中的属性,其中两个数组的属性都匹配。

最佳答案

您可以使用过滤器来提供查找

注意:我在某个我不记得的地方偷了过滤器“fromNative”,很抱歉不提供该内容

var app = angular.module('myApp', []);

app.controller('MainCtrl', function($scope) {


$scope.categories = [{
category: "work",
id: 1
}, {
category: "life",
id: 2
}
];

$scope.todos = [{
name: "Lift Up Hats",
category: "life",
date: "tomorrow"
}, {
name: "Wash the Horse",
category: "work",
date: "tomorrow"
}];
});

app.filter('fromNative', function () {
return function (native, options, matchField, valueField) {
if (options) {
for (var i = 0; i < options.length; i++) {
var o = options[i][matchField];
if (o === native) {
return options[i][valueField];
}
}
}
return '';
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<ul ng-app="myApp" ng-controller="MainCtrl">
<li ng-repeat="todo in todos | orderBy: 'completed'">
with {{todo.name}} my lookup is <b>{{ todo.category | fromNative : categories : 'category' :'id' }}</b>
</li>
</ul>

编辑我已经替换了我的待办事项以匹配您的示例

关于javascript - AngularJS 中不同范围的值匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36180865/

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