Muhammad Raihan Muhaimin
Muhammad Raihan Muhaimin

Reputation: 5729

Multiple ng-model from one ng

Dear all I am creating a checkbox where it will show the name of multiple item with its price, user can choose what he/she wants. In ng-model I need both the name of the item and the price. Here is one sample code I found.

    <div class="checkbox" ng-repeat="item in items">
      <label>
        <input ng-model="data[item.name + '||' + item.price]" type="checkbox" id="{{item.id}}">
        {{item.name}} with {{item.price | currency}}
      </label>
    </div>

And later on used string splitter to get the values. Is there any way I can get item.name and item.price using two different ng-model ?

Upvotes: 1

Views: 3707

Answers (1)

PSL
PSL

Reputation: 123739

No, You cannot use 2 ng-models for the same element, it does not make any sense as well.

Just set ng-model as a property on the item say selected

<input ng-model="item.selected" type="checkbox" id="{{item.id}}">

and since the item object itself has a price and name you can easily filter out the items selected and its respective name and price.

ex:

var selectedItems = $scope.items.filter(function(itm){return itm.selected});

If you want to set ngmodel as id with value as item properties (the way you have in your question) you could as well use ng-true-value (Though i think the previous approach should just suffice).

<input ng-model="data[item.id]" ng-true-value="{{item.name + '||' + item.price}}" type="checkbox" id="{{item.id}}">

Upvotes: 3

Related Questions