Maciej Laskowski
Maciej Laskowski

Reputation: 717

<select> AngularJS and ng-selected

I have HTML code like this:

 <div ng-controller="SimpleController">
    <select ng-model="item.category" ng-options="category as category.name for category in categories">
    </select> 
    <br />Item: {{item | json}}
 </div>

And js:

var app = angular.module("partnerModule", []);
app.controller("SimpleController", function($scope) {
    $scope.item = {category: {name:'Cat1', id: '1'}, name : "Item name"};
    $scope.categories = [{name:'Cat1', id: '1'}, {name: 'Cat2', id: '2'}, {name:'Cat3', id: '3'}];
});

I want to have already set option for "Cat1" when form is displayed. I tried to add something like this:

ng-selected="item.category.id == category.id"

For both <select> and <option> tags it didn't work

Upvotes: 0

Views: 50

Answers (1)

Rahul Arora
Rahul Arora

Reputation: 4543

This will work: html

 <div ng-controller="SimpleController">
    <select ng-model="item.category" ng-options="category as category.name for category in categories track by category.id">
    </select> 
    <br />Item: {{item | json}}
 </div>

In JS

var app = angular.module("partnerModule", []);
app.controller("SimpleController", function($scope) {
    $scope.item = {category: {name:'Cat1', id: '1'}, name : "Item name"};
    $scope.categories = [{name:'Cat1', id: '1'}, {name: 'Cat2', id: '2'}, {name:'Cat3', id: '3'}];
});

Upvotes: 1

Related Questions