我正在使用forEach循环遍历两个数组(蛋糕和结霜)。警报确认预期结果。 如何将结果添加到第3个数组? (cakeOptions) 这个小提琴展示了到目前为止的工作: http://jsfiddle.net/_StephenC/ov5syuwb/20/
由于
function CakeController($scope) {
$scope.cakes = [{
name: 'chocolate',
'price': 6
}, {
name: 'yellow',
'price': 5
}, {
name: 'coconut',
'price': 7
}
];
$scope.frostings = [{
'name': 'chocolate',
'price': 5
},
{
'name': 'vanilla',
'price': 5
}, {
'name': 'coconut',
'price': 8
}];
$scope.cakeOptions = [];
angular.forEach($scope.cakes, function (value, key) {
var thisCake = JSON.stringify(value.name);
angular.forEach($scope.frostings, function (value) {
var thisFrosting = JSON.stringify(value.name, value.value);
alert(thisCake + ' cake with ' + thisFrosting + ' frosting');
答案 0 :(得分:1)
我创建了一个实际上有效的新小提琴,并添加了从组合数组中填充第三个框的示例:
<强> HTML 强>
<div ng-app="cakeApp">
<div ng-controller="cakeCtrl">
<div id="one"><strong>Cakes</strong><br>
<div class="order" ng-repeat="cake in cakes">
{{cake.name}}
</div>
</div>
<div id="two"><strong>Frostings</strong><br>
<div class="order" ng-repeat="frosting in frostings">
{{frosting.name}}
</div>
</div>
<div id="three"><strong>Combinations</strong><br>
<div class="order" ng-repeat="cakeOption in cakeOptions">
{{cakeOption}}
</div>
</div>
</div>
</div>
<强> JAVASCRIPT:强>
var app = angular.module('cakeApp', []);
app.controller('cakeCtrl', ['$scope', function($scope) {
$scope.cakes = [{
name: 'chocolate',
price: 6
}, {
name: 'yellow',
price: 5
}, {
name: 'coconut',
price: 7
}];
$scope.frostings = [{
'name': 'chocolate',
'price': 5
},
{
'name': 'vanilla',
'price': 5
}, {
'name': 'coconut',
'price': 8
}];
$scope.cakeOptions = [];
angular.forEach($scope.cakes, function (value, key) {
var thisCake = JSON.stringify(value.name);
angular.forEach($scope.frostings, function (value) {
var thisFrosting = JSON.stringify(value.name, value.value);
$scope.cakeOptions.push(thisCake + ' cake with ' + thisFrosting + ' frosting');
});
});
}]);