我有这个对象
recipe = {
name : $scope.name,
ingredients : $scope.ingredients
}
我以两种不同的方式保存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
,并使用if
或else
等条件语句?
答案 0 :(得分:2)
如果定义了Glide
.with(myFragment)
.fromFile(fileName)
.centerCrop()
.into(myImageView)
,那么绑定它,否则绑定ingr.ingredient
,即:
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'];
})
答案 1 :(得分:0)
如果您知道自己永远不会有第三种变体
<li ng-repeat="ingr in recipe.ingredients track by $index">
{{ingr.ingredient || ingr}}
</li>
但是,这不是可维护的。我认为将这个逻辑委托给辅助函数可能会更清晰。
<li ng-repeat="ingr in getIngredients(recipe.ingredients)">
{{ingr}}
</li>
function getIngredients(ingredients) {
// Logic to flatten your mix of objects and strings
}
这将允许您添加/更改配方成分的模型,同时还可以创建可以单独进行单元测试的逻辑
答案 2 :(得分:0)
有几种方法,都在这里列出。 这是一个Plunkr
angular.module('myApp',[])
.controller('myCtrl', function($scope){
$scope.array1 = [{ingredient : 'berry'}, {ingredient : 'honey'}]
$scope.array2 = ['berry', 'honey'];
$scope.array3 = [{ingredient : 'berry'}, {ingredient : 'honey'}, 'berry', 'honey'];
});
<h1>array 1</h1>
<li ng-repeat="ingr in array1">
<b>{{ ingr.ingredient || ingr }}</b>
</li>
<h1>array 2</h1>
<li ng-repeat="ingr in array2">
<b>{{ ingr.ingredient ? ingr.ingredient : ingr }}</b>
</li>
<h1>array 3</h1>
<li ng-repeat="ingr in array3">
<b>{{ ingr.ingredient || ingr }}</b>
</li>
<li ng-repeat="ingr in array3">
<b>{{ ingr.ingredient ? ingr.ingredient : ingr }}</b>
</li>