在angularjs中设置作用域值等于数组元素

set scope value equal to array element in angularjs

本文关键字:数组元素 作用域 angularjs 设置      更新时间:2023-09-26

我仍然是新的JavaScript,我想知道如何设置$scope值等于另一个数组的值,并在另一个函数中使用它。这就是我要做的:

(function () {
    'use strict';
    angular
        .module('app')
        .controller('LanguageController', LanguageController);
    LanguageController.$inject = ['$scope','$translate'];
    function LanguageController($scope,$translate) {

        $scope.lang = [
            "Nederlands",
            "Français",
            "English",
            "Deutsch",
            "Español"
        ];
        $scope.selectLang = $scope.lang[0];
        $scope.changeLang = function(){
            console.log("Lang === " + $scope.selectLang);
        }
        // When value of $scope lang change i would want do 
        //Change the value of this 
        $scope.langI18n = [
            "nl_NL",
            "fr_FR",
            "en_US",
            "de_DE",
            "es_ES"
        ];
        //And then use it here 
        $scope.setLang = function(langKey) {
            // You can change the language during runtime
            console.log("change to " +langKey )
            $translate.use(langKey);
        };
    }
})(); 

我知道$scope.langI18n是错误的,但我想知道我如何能改善这一点,所以它确实工作。

$scope.lang设置时,我想到了一个可能的解决方案,使用一个函数将索引与数组langI18n进行比较,然后将语言值设置为setlang,但我需要一些启动。

您可以在这里使用对象数组。

$scope.langs = [
    {"nl_NL": "Nederlands"},
    {"fr_FR": "Français"},
    {"en_US": "English"},
    {"de_DE": "Deutsch"},
    {"es_ES": "Español"}
];