简体   繁体   English

如何使所选值与 AngularJS 中的选项值不同?

[英]How to make selected value different than options value in AngularJS?

How can I make the selected value different than the values given in options with select in AngularJS.如何使所选值与 AngularJS 中的 select 选项中给出的值不同。 Here is what I have now:这是我现在拥有的: 在此处输入图像描述

What I want to achieve is, to display the selected value as "EN", but the options inside to be "English", "Italian",...我想要实现的是,将所选值显示为“EN”,但里面的选项是“English”,“Italian”,......

Below is my HTML Code for the select element:下面是我的 select 元素的 HTML 代码:

<select class="select-language d-md-none d-inline-block" ng-options="lang.Lang_Code for lang in languagesMenu" 
        ng-model="language" ng-change="changeLanguage()" ng-cloak>
</select>

This is my JavaScript for the languagesMenu:这是我的语言菜单的 JavaScript:

// navigation languages
    $scope.languagesMenu = [
        {
            Language: "English",
            Country: "USA",
            Code: "en/us/",
            Lang_Code: "en"
        }, {
            Language: "Italian",
            Country: "IT",
            Code: "it/it/",
            Lang_Code: "it"
        }
    ]

And this is the changeLanguage function:这是changeLanguage function:

// change language 
    $scope.changeLanguage = function () {
        $window.open($scope.language.Code, '_self');
    }

How can I make the options to be the "Language" from the JSON array, and the selected value to be the "Lang_Code"?如何将选项设置为 JSON 数组中的“语言”,并将所选值设置为“Lang_Code”?

The following snippet might help where we:以下代码段可能对我们有所帮助:

  • use ng-options="item.Language for item in languagesMenu " to select which property within the languagesMenu object gets displayed使用ng-options="item.Language for item in languagesMenu "到 select 显示语言菜单 object 中的哪个属性
  • and then we use $scope.selectedName.Code which takes the Code property from our selected object (thanks to ng-model ) to go to redirect to the relevant page然后我们使用$scope.selectedName.CodeCode属性从我们选择的 object (感谢ng-model )到 go 重定向到相关页面

 var app = angular.module('myApp', []); app.controller('myCtrl', function($scope, $window) { $scope.languagesMenu = [{ Language: "English", Code: "us/" }, { Language: "Italian", Code: "it/" }, { Language: "Chinese", Code: "cn/" } ]; $scope.changeLanguage = function() { $window.open($scope.selectedName.Code, '_self'); } });
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script> <div ng-app="myApp" ng-controller="myCtrl"> <select ng-model="selectedName" ng-options="item.Language for item in languagesMenu " ng-change="changeLanguage()"> </select> Selected language: {{selectedName.Code }} </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM