我在 ng-repeat
中创建按钮并为每个按钮设置值。
我想从选定的按钮获取值并添加到数组,如果单击其他按钮,也将值作为对象添加到数组。
如果再次单击同一个按钮,该值应该从数组中删除对象。
<div ng-repeat="room in Rooms">
...
<button id="HR_{{room.Id}}" value="{{room.Id}}" onclick="AddToCart({{room.Id}})">Add To Cart</button>
</div>
Javascript:
var cartlist = [];
function AddToCart(n) {
var c = $("#cartcount").text();
cartlist.push({
Id: n,
});
$("#cartcount").text(parseInt(c) + 1);
}
此代码 onclick="AddToCart({{room.Id}})"
导致错误。我使用 ng-click
但无法得到答案。
最佳答案
对于您需要的这种行为,使用相同的按钮添加或删除您需要添加一些逻辑来检查元素是否在数组中。你可以这样做:
HTML:
selectedRooms: {{selectedRooms}}
<div ng-repeat="room in rooms">
<button ng-click="Add_Remove_Room(room.id)">Add / Remove {{room.name}}</button>
</div>
Controller :
angular.module('tAngularApp')
.controller('MainCtrl', ["$scope", "$rootScope", function ($scope, $rootScope) {
this.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
$scope.rooms = [
{id:1, name: "Room #1"},
{id:2, name: "Room #2"},
{id:3, name: "Room #3"},
{id:4, name: "Room #4"}
];
$scope.selectedRooms = [];
$scope.Add_Remove_Room = function (roomID) {
var index = $scope.selectedRooms.indexOf(roomID);
if(index === -1){
// If is not selected the room -> add it
$scope.selectedRooms.push(roomID);
} else {
// If is selected the room -> remove it
$scope.selectedRooms.splice(index, 1);
}
}
}]);
关于javascript - 我怎么知道点击了哪个按钮作为对象添加到 ng-repeat 中的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41382513/