K.Dzien
K.Dzien

Reputation: 177

Angularjs: input for ng-repeat elements

Sorry for my language skills, hope you understand all.

I need to make inputs for ng-repeat elements, to pass input data to http post. For example: i have 4 elements, for all elements i make inputs, and f.e:

elem1- input: 1 
elem2- input: 4 
elem3- input: 1 
elem4- input: 2 

Here is my code:

.panel-body.note-link ng-repeat=("meal in mealsList track by $index")
                    a data-toggle="tab" 
                      h4.pull-right.text-muted
                        | {{meal.price}} zł

                    h4.text-success
                        i.fa.fa-close.text-danger<> ng-click="removeMeal($index)" style="cursor: pointer;font-size: 15px;"
                        | {{meal.name}} {{$index}}
                        input.form-control type="number"  ng-model="example"
                        | {{example}}

And i dont know, how to pass input data to controller. Any tips,tricks?

Upvotes: 0

Views: 82

Answers (3)

Rob
Rob

Reputation: 1860

Repeat through your mealList array and add the inputs.

Example: https://jsfiddle.net/ptzhL0uL/

Controller

function Controller1($scope) {
  var vm = this;

  vm.items_saved = false;
  vm.mealList = [{
    price: '2.99',
    name: 'Pizza'
  }, {
    price: '1.99',
    name: 'Chips'
  }, {
    price: '4.99',
    name: 'Beer'
  }];

  vm.addNewItem = addNewItem;
  vm.saveItems = saveItems;

  function addNewItem() {
    vm.mealList.push({});
  }

  function saveItems() {
    vm.items_saved = true;
  }
}

HTML

<button ng-click="ctrl.addNewItem()" class="btn btn-default">Add Item</button>
<div ng-repeat="item in ctrl.mealList">
  <input type="text" ng-model="item.name">
  <input type="text" ng-model="item.price">
  <input type="number" ng-model="item.quantity">
</div>
<button ng-click="ctrl.saveItems()" class="btn btn-primary">Save</button>
<hr>
<div ng-if="ctrl.items_saved">
  <h4>Here is your meal list:</h4>
  <ul>
    <li ng-repeat="item in ctrl.mealList">{{item.quantity}}{{item.name}} at ${{item.price}} each</li>
  </ul>
</div>

Upvotes: 1

Kobi Cohen
Kobi Cohen

Reputation: 678

angular.module('yourModule').controller('viewController', function($scope) {
  $scope.mealList = [...];
  $scope.example; //The input data will automatically bind to this variable.
});

If you want the input to change data within your meal object, then do this:

input.form-control type="number"  ng-model="meal.example"

And then the property value of the meal object would bind to the input

Upvotes: 1

Kyle
Kyle

Reputation: 5557

Just attach it to the ngModel directive.

<div ng-repeat="item in array">
    {{ item.output }}

    <input ng-model="item.output" />
</div>

Upvotes: 0

Related Questions