black bamba
black bamba

Reputation: 57

get object from datalist ng-repeat angular

I got datalist such as below ,and color a color object with name and id properties.

<datalist id="opts">
<option ng-repeat="color in colors" value = "{{color.id}}">color.name</option>
</datalist>

My problem is that i want to run a function with the id and the name of the selected color. how can i access both of them without show the id on the view?

<button ng-click="someFunction(color.id,color.name)">button </button>

Upvotes: 1

Views: 5945

Answers (3)

Desa Kumaaran
Desa Kumaaran

Reputation: 5

Use Angular Expression to Bind {{color.name}} in option or use Value attribute

<option ng-repeat="color in colors" value = "{{color.id}}" ng-change="someFunction(color )">{{color.name}}</option>

You can also give a try to use

ng-change
in side the datalist Example:

<datalist id="opts">
<option ng-repeat="color in colors" value = "{{color.id}}" ng-change="someFunction(color )">{{color.name}}</option>
</datalist>

Now With in the Function You can Access both the id and name...For this No need of submit button

 $scope.someFunction = function(colorobj){
       var colorid=colorobj.id;
       var colorname=colorobj.name;
    }

Upvotes: 0

Shashank
Shashank

Reputation: 2060

You can do as illustrated below.

Pass directly the object - 'color' and access the 'id', 'name', etc in the controller.

HTML:

  <button ng-click="someFunction(color)">button </button>

JS:

$scope.someFunction = function (colorObj) {
      // access colorObj.id, colorObj.name, etc.
}

Upvotes: -1

Pankaj Parkar
Pankaj Parkar

Reputation: 136154

You should do it manually, as ng-options directive would be good option to go, but unfortunately it doesn't supported for datalist. To get selected value inside controller scope you need to add ng-model to datalist

Markup

<datalist id="opts" ng-model="selectedColor">
   <option ng-repeat="color in colors" value = "{{color.id}}">color.name</option>
</datalist>

<button ng-click="someFunction(selectedColor)">button</button>

And then do filter on color collection inside controller someFunction

$scope.someFunction = function(){
    var selected = $filter('filter')($scope.colors, {id: parseInt(selectedColor)}, true),
        selectedColor;
    if(selected){
       selectedColor = selected[0];
    }
}

Upvotes: 2

Related Questions