I'm new to Angular so please be gentle :)
I am recieving a "Brand" Object from the server and I want to set the select field with the good corresponding value.
Brands look like this :
Brands = [{name: "BRAND1", id=242},
{name: "BRAND2", id=562}]
And I got from the server:
brandFromTheServer = {name: "BRAND2", id=562};
This is my select :
<select id="brand" ng-model="product.brand" class="form-control" ng-options="brand as brand.name for brand in brands"></select>
And I want the select to be set with brandFromTheServer.
I tried in the controller:
$scope.product.brand = brandFromTheServer;
How can I set the value of the select with the brand that I'm recieving ?
Sorry, my English is terrible ! Please help :=)
<select id="brand" ng-model="product.brand" class="form-control" ng- options="brand as brand.name for brand in brands">
<option value="o">Val 1</option>
<option value="1">Val 2</option>
<option value="2">Val 3</option>
</select>
$scope.product.brand = 0 or 1 or 2;
I use something like this:
<select ng-options="option.name for option in advertiserList" ng-model="selectedOption.advertiserChoice" class="form-control"></select>
And in my controller I have:
$scope.advertiserList = response.advertisers;
var data = $scope.advertiserList.getIndexBy("id", $scope.currentAdvertiser.id)
$scope.selectedOption.advertiserChoice = $scope.advertiserList[data];
The method getIndexBy() is like this:
Array.prototype.getIndexBy = function (name, value) {
for (var i = 0; i < this.length; i++) {
if (this[i][name] === value) {
return i;
}
}
}
And my advertiserList json looks like this:
"advertisers": [
{
"id": 1,
"name": "Somebody Franck",
},
{
"id": 2,
"name": "Me Me me",
}
]
Your approach is correct when using ng-options, however the product.brand
is not bound to the Brand object. Something like this works:
Controller:
$scope.brands = [
{
name: '1'
},
{
name: '2'
},{
name: '3'
}
];
$scope.product = {
brand: $scope.brands[1] // now it has a 'reference'
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.