Reputation: 170
I create buttons in ng-repeat
and set value for each one.
I want to get the value from a selected button and add to array, and, if clicked other buttons, also add the value to the array as an object.
If clicked again the same button, the value should be removed object from the array.
<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);
}
this code onclick="AddToCart({{room.Id}})"
cause an error. I use ng-click
but I could not get an answer.
Upvotes: 3
Views: 589
Reputation: 2197
For this behavior that you need, add or remove with the same button you need to add some logic to check if the element is in the array or not. you can do something like:
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);
}
}
}]);
Upvotes: 4
Reputation: 2058
Use ng-click and remove the interpolation.
<button id="HR_{{room.Id}}" value="{{room.Id}}" ng-click="AddToCart(room.Id)">Add To Cart</button>
Upvotes: 1
Reputation: 2834
This is already answered in this question: Adding parameter to ng-click function inside ng-repeat doesn't seem to work
This was the answer:
Instead of
<button ng-click="removeTask({{task.id}})">remove</button>
do this:
<button ng-click="removeTask(task.id)">remove</button>
Please see this fiddle:
http://jsfiddle.net/JSWorld/Hp4W7/34/
Upvotes: 2
Reputation: 3261
You should use ng-click
instead like so:
ng-click="AddToCart(room.Id)"
Upvotes: 0