user4895544
user4895544

Reputation: 103

Select dropdown value based on value in DB

I am new to angular JS. I have a dropdown box where static options with values are present. Based on condition I have to select the default value which matches the value from Database. How can it be achieved? model="TemplateObj.IsActive" has the int value 0,1 or 2 from DataBase.

  <label class="">STATUS</label>
<select class="form-control input-sm" style="border: none" required ng-model="TemplateObj.IsActive" >
 <option value="2">In Development</option>
 <option value="1">Active</option>
 <option value="0">InActive</option>
 </select>

Upvotes: 0

Views: 1815

Answers (3)

Roh&#236;t J&#237;ndal
Roh&#236;t J&#237;ndal

Reputation: 27202

Try ngOptions instead of normal HTML select.

DEMO

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl',function($scope) {
    
    $scope.status = [{
        title: 'In Development',
        value: 2
    }, {
        title: 'Active',
        value: 1
    }, {
        title: 'Inactive',
        value: 0
    }];
    
    $scope.TemplateObj = {
     "IsActive": 1
    } 
    
    
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
  <select ng-model="TemplateObj.IsActive" ng-options="option.value as option.title for option in status"></select>
</div>

Upvotes: 0

flashjpr
flashjpr

Reputation: 470

An option would be to make use of the ng-options directive.

The documentation is here and there are quite a few examples you can guide from.

Upvotes: 1

TheSameSon
TheSameSon

Reputation: 369

Use ng-options directive with array of statuses. The syntax may look a bit complicated for beginner, but you'll learn it someday: value as title for element in array

JS:

$scope.statuses = [{
    title: 'In Development',
  value: 2
}, {
    title: 'Active',
  value: 1
}, {
    title: 'Inactive',
  value: 0
}];

HTML:

<select ng-model="TemplateObj.IsActive" ng-options="status.value as status.title for status in statuses"></select>

Here is jsfiddle with working example.

Upvotes: 1

Related Questions