Reputation: 15
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
Reputation: 691695
You're pretty confused between your various attributes:
$scope.myColor = $scope.colors[2].value;
color.name ==
myColor
value="{{color.shade}}"
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
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