3

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.

Khoshtarkib
  • 170
  • 12

4 Answers4

4

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

}]);
Yoan
  • 2,158
  • 1
  • 12
  • 21
2

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/

Community
  • 1
  • 1
C. Molendijk
  • 2,614
  • 3
  • 26
  • 35
1

Use ng-click and remove the interpolation.

<button id="HR_{{room.Id}}"  value="{{room.Id}}" ng-click="AddToCart(room.Id)">Add To Cart</button>
Balaji Marimuthu
  • 1,940
  • 13
  • 13
0

You should use ng-click instead like so:

ng-click="AddToCart(room.Id)"

Nora
  • 3,093
  • 2
  • 20
  • 22