FDavidov
FDavidov

Reputation: 3675

Angular ng-repeat for a select, setting one option as selected using $rootScope variable

I have the following select:

<select class="form-control" 
        onchange="User_Changed_Language()" 
        id="HeaderLanguageSelection" 
        style="cursor:pointer;width:100%;height:30px;margin:0;padding:0" 
        title="{{Labels.Change_Language_Tooltip}}">
    <option ng-repeat="One_Language in Languages_List" 
            value="{{One_Language.Code}}" 
            ng-selected="One_Language.Code == current_Language">
        {{One_Language.Name}}
    </option>
</select>

Now, current_Language is a $rootScope variable with a value (e.g. "EN"). I want the select element to display the selected value instead of the very first. What am I doing wrong?

One more note: I know that I could use ng-click, but I don't think this is the source of the issue.

Thanks.

Upvotes: 3

Views: 3066

Answers (1)

beaver
beaver

Reputation: 17647

Check this snippet:

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

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

  $scope.Labels = {Change_Language_Tooltip: "change lang"};
  $scope.Languages_List = [
    { name: 'English', Code: 'en' },
    { name: 'Espanol', Code: 'es' },
    { name: 'Italian', Code: 'it' }];
  $rootScope.current_Language = $scope.Languages_List[1];

});
<!DOCTYPE html>
<html ng-app="app">

<head>
  <meta charset="utf-8" />
  <script src="https://code.angularjs.org/1.3.15/angular.js"></script>
  <script src="app.js"></script>
</head>

<body ng-controller="MainCtrl">
  <p>selected item is : {{current_Language}}</p>

  <select class="form-control" 
  onchange="User_Changed_Language()" 
  id="HeaderLanguageSelection" 
  style="cursor:pointer;width:100%;height:30px;margin:0;padding:0" 
  title="{{Labels.Change_Language_Tooltip}}" 
  ng-options="item.name for item in Languages_List track by item.Code"
  ng-model="current_Language">
  </select>

</body>

</html>

PS: the selected item (default or initial) must be one element of the items used in the ngOptions list

Upvotes: 3

Related Questions