AngularJS Dropdown语言选择

时间:2015-10-20 12:56:58

标签: javascript html angularjs html5

对于学校项目我正在使用AngularJS创建一个应用程序。我正在尝试创建一个下拉菜单,使用按钮设置所选语言。

JS:

app.controller('NavCtrl',['$scope','$translate', function($scope,$translate){

    $scope.languages = [
        { language: "en", },
        { language: "nl" }
    ];

    $scope.selectedlanguage = $scope.languages[1];

    $scope.ChangeLanguage = function (lang) {
        $translate.use(lang);
    }

}])

HTML:

<div ng-controller="NavCtrl">
    <select ng-model="selectedlanguage" 
            ng-change="option(this.selectedlanguage)" 
            ng-options="i.language for i in languages">
    </select>
    {{selectedlanguage.language}}
    <button class="button button-clear" 
            ng-click="ChangeLanguage('{{selectedlanguage.language}}')">
         Set language
    </button>
</div>

此时按钮始终将我的语言设置为[1](nl),如何将语言设置为下拉菜单中选择的语言?

4 个答案:

答案 0 :(得分:3)

无需将其包装在<div ng-controller="NavCtrl"> <select ng-model="selectedlanguage" ng-change="option(this.selectedlanguage)" ng-options="i.language for i in languages"> </select> {{selectedlanguage.language}} <button class="button button-clear" ng-click="ChangeLanguage(selectedlanguage)"> Set language </button> </div>

{{1}}

答案 1 :(得分:2)

我可以看到一些问题。

首先,您不需要视图中的this.selectedLanguage,因为$scope会自动被视为您的上下文:

ng-change="option(selectedlanguage)"

第二次,在您的控制器中,您将$scope.selectedlanguage设置为i,然后将其绑定到视图中的i.language。要解决此问题,请尝试:

ng-options="i as i.language for i in languages"

x as y语法允许您将x绑定到模型,同时为您的下拉标签显示y

https://docs.angularjs.org/api/ng/directive/ngOptions

第三次,正如@Matthew Berg指出的那样,您不需要点击处理程序中的{{...}}

ng-click="ChangeLanguage(selectedlanguage.language)"

这里有一切工作的傻瓜:

http://plnkr.co/edit/YZf3vsKQEucOsKFLlYoQ?p=preview

答案 2 :(得分:1)

使用此代码::::

  <div ng-controller="NavCtrl">
       <select ng-model="selectedlanguage" ng-change="option(selectedlanguage)" ng-options="i as i.language for i in languages"></select>
        {{selectedlanguage.language}}
       <button class="button button-clear" ng-click="ChangeLanguage(selectedlanguage)">Set language</button>
  </div>

答案 3 :(得分:1)

你能检查$ scope.ChangeLanguage函数里面的lang值吗?我认为它总是{{selectedlanguage.language}}。

变化:     &#34; ChangeLanguage(selectedlanguage.language)&#34;