Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I know which button was clicked to add as an object to array in the ng-repeat?

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.

like image 388
Khoshtarkib Avatar asked Dec 18 '25 13:12

Khoshtarkib


2 Answers

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);
        }
    }

}]);
like image 103
Yoan Avatar answered Dec 21 '25 03:12

Yoan


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/

like image 32
C. Molendijk Avatar answered Dec 21 '25 03:12

C. Molendijk