我想使用AngularJs实现一个功能,例如,
每次单击一种成分时,所选列表都会更改,并添加另一种成分并显示编号,如果重复单击一种成分,则只需更改该成分的量
here is my html
<div ng-app="myApp" ng-controller="addIngredientCtrl">
<div class="ingredient-list">
<h4>INGREDIENT:</h4>
<ul ng-repeat="items in item.recipe.IngredientMapping">
<li class="ingredient-list-style">
<img src="http://164.132.196.117/chop_dev/api/AngularJs/images/plus.png" class="plus-size" ng-click="addIngredient(items.Ingredient.name)">
{{items.quantity}} {{items.Unit.name}} {{items.Ingredient.name}}
</li>
</ul>
</div>
<div class="selected-list-box">
<div class="selected-list">
<h4>Selected List</h4>
<div>
<ul ng-repeat="selectedItem in selectedItem track by $index">
<li>
{{selectedItem}}
<li ng-repeat="(c, n) in results"> {{c}} shows {{n}} times</li>
</li>
</ul>
</div>
</div>
</div>
这是我的js
myApp.controller('addIngredientCtrl', function($scope) {
$scope.selectedItem=Array();
$scope.addIngredient= function(param){
$scope.selectedItem.push(param);
console.log($scope.selectedItem);
$scope.results = {};
for (var i = 0; i < $scope.selectedItem.length; i++) {
var selected = $scope.$scope.selectedItem[i];
if(selected) {
if ($scope.results.hasOwnProperty(selected)) {
$scope.results[selected]++;
} else {
$scope.results[selected] = 1;
}
}
}
最佳答案
您在代码中两次有$ scope
var selected = $scope.$scope.selectedItem[i];
var myApp = angular.module('myApp',[]);
myApp.controller('addIngredientCtrl', function($scope) {
$scope.item = {
recipe:{
IngredientMapping:[
{quantity:1,Unit:{name:'kg'},Ingredient:{name:"onion"}}
]
}
};
$scope.selectedItem=Array();
$scope.addIngredient= function(param){
console.log($scope.selectedItem);
$scope.selectedItem.push(param);
$scope.results = {};
for (var i = 0; i < $scope.selectedItem.length; i++) {
var selected = $scope.selectedItem[i];
if(selected) {
if ($scope.results.hasOwnProperty(selected)) {
$scope.results[selected]++;
} else {
$scope.results[selected] = 1;
}
}
}
}
});
<style>
.plus-size{height:16px;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="addIngredientCtrl">
<div class="ingredient-list">
<h4>INGREDIENT:</h4>
<ul ng-repeat="items in item.recipe.IngredientMapping">
<li class="ingredient-list-style">
<img src="http://164.132.196.117/chop_dev/api/AngularJs/images/plus.png" class="plus-size" ng-click="addIngredient(items.Ingredient.name)">
{{items.quantity}} {{items.Unit.name}} {{items.Ingredient.name}}
</li>
</ul>
</div>
<div class="selected-list-box">
<div class="selected-list">
<h4>Selected List</h4>
<div>
<ul ng-repeat="selectedItem in selectedItem track by $index">
<li>
{{selectedItem}}
<li ng-repeat="(c, n) in results"> {{c}} shows {{n}} times</li>
</li>
</ul>
</div>
</div>
</div>