gpt4 book ai didi

javascript - Angular ng-repeat 有一些逻辑

转载 作者:行者123 更新时间:2023-11-30 16:15:11 25 4
gpt4 key购买 nike

我有这个对象

recipe = {
name : $scope.name,
ingredients : $scope.ingredients
}

我以两种不同的方式保存成分,即

ingredients1 = [{ingredient : 'berry'}, {ingredient : 'honey'}]
ingredients2 = ['berry', 'honey'];

在 ng-repeat 中,我需要根据条件传递成分;

//ingredients1
<li ng-repeat="ingr in recipe.ingredients track by $index">
<b>{{ingr}}</b>
</li>

//ingredients2
<li ng-repeat="ingr in recipe.ingredients track by $index">
<b>{{ingr.ingredients}}</b>
</li>

我可以为这两种情况制作 1 个 ng-repeat,并使用一些条件语句,如 ifelse 吗?

最佳答案

如果定义了 ingr.ingredient 则绑定(bind)它,否则绑定(bind) ingr:

{{!!ingr.ingredient ? ingr.ingredient : ingr}}

试试这段代码:

angular.module('myApp', [])
.controller('MyCtrl', function($scope, $http) {
var myScope = this;
myScope.ingredients = [{
ingredient: 'berry'
}, {
ingredient: 'honey'
}, 'berry', 'honey'];
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
<ul ng-app="myApp" ng-controller="MyCtrl as c">
<li ng-repeat="ingr in c.ingredients track by $index">
<b>{{!!ingr.ingredient ? ingr.ingredient : ingr}}</b>
</li>
</ul>

关于javascript - Angular ng-repeat 有一些逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35631866/

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