user3787969
user3787969

Reputation: 15

ng-model not work with ng-repeat in dropdown list

I need to show image in option list, I couldn't use with ng-options so, I preferred to ng-repeat to show image with default selected item but in this I couldn't get the selected value from ng-change. ng-model not work here, whether I did any wrong?

The code is this:

function MyCntrl($scope) {
$scope.colors = [
{name:'black', value:'st1',
url: 'plain_50.jpg',
},
{name:'white', value:'st2',
    url: 'plain_50.jpg',
},
{name:'red', value:'st3',
    url: 'plain_50.jpg',
}
];
$scope.myColor = $scope.colors[2].value; 

$scope.change = function(val){
console.log(val);
}
}

<div ng-controller="MyCntrl">
<select  ng-model="selectClr" ng-change="change(selectClr.value)" >
<option value="">Select a color</option>                                
<option ng-repeat="color in colors" value="{{color.shade}}" ng-selected="{{color.name == 
myColor}}" style="background:url(http:{{color.url}}) no-repeat 8px 0px;" 
>{{color.name}}   </option></select>

Upvotes: 0

Views: 4575

Answers (2)

JB Nizet
JB Nizet

Reputation: 691695

You're pretty confused between your various attributes:

  • The JS code set the preselected option using the value: $scope.myColor = $scope.colors[2].value;
  • but the HTML code selects the current color if its name: color.name == myColor
  • and the value of the option is set to the color shade (which doesn't even exist in the model): value="{{color.shade}}"
  • the select uses selectClr instead of myColor, which is the value of the selected color.

Make all this coherent, and the code will work fine: http://plnkr.co/edit/4BPMosJkyg3CcfCqtjIB?p=preview

<div ng-controller="MyCntrl">
  <select ng-model="myColor" ng-change="change(myColor)" >
    <option value="">Select a color</option>                                
    <option ng-repeat="color in colors" 
            value="{{color.value}}" 
            ng-selected="{{color.value == myColor}}">
      {{color.name}}
    </option>
  </select>
</div>

function MyCntrl($scope) {
  $scope.colors = [
    {
      name:'black', 
      value:'st1'
    },
    {
      name:'white', 
      value:'st2'
    },
    {
      name:'red', 
      value:'st3'
    }
  ];

  $scope.myColor = $scope.colors[2].value; 

  $scope.change = function(val){
    console.log(val);
  }
}

Upvotes: 0

Hargrovm
Hargrovm

Reputation: 1063

I think you want the ngOption directive instead of the ngRepeat.

Please see the following documentation https://docs.angularjs.org/api/ng/directive/select

And note the comment regarding the use of ngOption and not ngRepeat

Upvotes: 1

Related Questions