How to set the ng-selected value in angularjs?

Viewed 154

I am using the following code in my project. I have a select element in my angular js project. for options iam passing the json values using ng-repeat. but for ng-selected, I want to show the JSON first value.

I tried two options but it doesn't work for me. If anyone knows how to fix this please let me know.

My HTML code( option one and two):

  <select select2 id="environment" name="authorization" ng-model='addNlpStepForm.restfulEntity.authorization' class="md-form-control">
        <option ng-repeat="(key,value) in authorizationtype" value="{{key}}"
          ng-bind="value" ng-selected="addNlpStepForm.restfulEntity.authorization == 1"> 
        </option>
  </select>

<select select2 id="environment" name="authorization" ng-model='addNlpStepForm.restfulEntity.authorization' class="md-form-control">
        <option ng-repeat="(key,value) in authorizationtype" value="{{key}}"
          ng-bind="value" ng-selected="key == 1"> 
        </option>
  </select>

My JSON code:

AUTHORIZATION_TYPES = {
  1 : "None",
  2 : "Basic",
  3 : "Bearer",
};
2 Answers

This is what i did in my code when i wanted to display a json list by using ngFor, I tried to implement it on your example! Hope is works:

<select formControlName="type">
    <option *ngFor="let type of AUTHORIZATION_TYPES" [ngValue] ="type.key"> {{type.value}}  </option>
</select>

*** I also use the reactive-form approach

Please check this

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

app.controller('MainCtrl', function($scope) {

    $scope.AUTHORIZATION_TYPES = {
  1 : "None",
  2 : "Basic",
  3 : "Bearer",
};
     
});
<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.0.x" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js" data-semver="1.0.8"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
  <select select2 id="environment" name="authorization" class="md-form-control">
        <option ng-repeat="(key,value) in AUTHORIZATION_TYPES" value="{{key}}"
          ng-bind="value" ng-selected="key == 1"> 
        </option>
  </select>
  </body>

</html>

Related