user2537154
user2537154

Reputation:

How to push an element from an ng-repeat into another

The problem is that I don't know and I didn't found how to do what's written in the title. How do I grab the element whose link is being clicked, and then push its value into an array?

Demo at Plunker

from app.js

  $scope.orderList = [];
  $scope.add = function() {
    $scope.orderList.push($scope.pizza.name);
  };

from view.html

<div ng-controller="orderCtrl">
  <input type="text" ng-model="search" placeholder="{{placeholder}}" ng-focus="example()" ng-blur="default()" />
    <ul ng-hide="pizzaSvg">
      <li ng-repeat="pizza in pizze | filter:search | orderBy: 'name'" ng-model="orderList"><a href="" ng-click="add()">{{pizza.name}}</a><br/>{{pizza.ingredients}}</li>
    </ul>
    <ul ng-show="pizzaSvg">
      <li ng-repeat="order in orderList"><a href="">[x]</a> {{order}}</li>
    </ul>
</div>

Upvotes: 1

Views: 350

Answers (2)

Duncan
Duncan

Reputation: 95672

You need to pass your pizza as a parameter to the add function:

  $scope.orderList = [];
  $scope.add = function(pizza) {
    $scope.orderList.push(pizza.name);
  };

Then in your html:

<div ng-controller="orderCtrl">
  <input type="text" ng-model="search" placeholder="{{placeholder}}" ng-focus="example()" ng-blur="default()" />
    <ul ng-hide="pizzaSvg">
      <li ng-repeat="pizza in pizze | filter:search | orderBy: 'name'" ><button ng-click="add(pizza)">{{pizza.name}}</button><br/>{{pizza.ingredients}}</li>
    </ul>
    <ul ng-show="pizzaSvg">
      <li ng-repeat="order in orderList"><button>[x]</button> {{order}}</li>
    </ul>
</div>

Also, avoid using <a> for clickable elements, usually something like <button> will work more cleanly as the browser won't try to follow a link as its default click action.

Upvotes: 3

unflores
unflores

Reputation: 1810

I would typically do this with a button like so:

<ul ng-show="pizzaSvg">
  <li ng-repeat="order in orderList"><button ng-click="add(order)">[x]</a> {{order}}</li>
</ul>

The reasoning is because a link in my view is meant for moving from page to page, where as a button will be used to execute an action.

Upvotes: 0

Related Questions