tobiased
Goto Top

Angularjs: ng-click übergabe einzelner Parameter

Hallo community,

ich arbeite gerade an einem online Warenkorb für Pizzas und benutze dafür angularjs. Ich habe eine JSON Datei in der alle Artikel wie folg aufgelistet sind.
{"name": "Pizza Salami", "price": 4}

Meine app.js sieht wie folgt aus:
angular.module('PizzaApp', )  
  .factory('Cart', function() {  
    var items = ;
    return {
      getItems: function() {
        return items;
      },
      addPizza: function(pizza) {
        items.push(pizza);
      },
      sum: function() {
        return items.reduce(function(total, pizza) {
          return total + pizza.price;
        }, 0);
      }
    };
  })
  .controller('PizzasCtrl', function($scope, $http, Cart){  
    $scope.cart = Cart;
    $http.get('pizzas.json').then(function(pizzasResponse) {  
      $scope.pizzas = pizzasResponse.data;
    });
  })
  .controller('CartCtrl', function($scope, Cart){  
    $scope.cart = Cart;
  });

Nun möchte ich mit ng-click die einzelnen Pizzas hinzufügen, was mit folgenem Code auch funktioniert.

<table class="table" ng-controller="PizzasCtrl">  
      <tr ng-repeat="pizza in pizzas">  
        <td>{{pizza.name}}</td>
        <td>{{pizza.price}}</td>
        <td><a href class="btn btn-default btn-sm" ng-click="cart.addPizza(pizza);">Hinzufügen</a></td>  
      </tr>
    </table>

Meine Frage nun, kann ich auch ohne ng-repeat ein bestimmten Parameter übergeben?
Also zum Beispiel durch
ng-click="cart.addPizza(pizza.1)   
nur das 1 Element der Scope.

Content-Key: 300409

Url: https://administrator.de/contentid/300409

Printed on: April 23, 2024 at 14:04 o'clock

Mitglied: 114757
Solution 114757 Mar 30, 2016 updated at 17:58:44 (UTC)
Goto Top
Moin,
ich würd's mal so versuchen
ng-click="cart.addPizza(pizzas)"  
"pizzas" ist ja auch nur ein Array von Objekten.

Gruß jodel32
Member: Tobiased
Tobiased Mar 30, 2016 at 18:11:45 (UTC)
Goto Top
Hallo jodel32

vielen dank für deine Antwort hat geholfen face-smile

Gruß Tobias