我想要一个下拉列表来更改网站显示的语言,所以我目前有:
<select ng-controller="langCtrl">
<option ng-click="switchLanguage('en')" value="en">EN</option>
<option ng-click="switchLanguage('de')" value="de">DE</option>
<option ng-click="switchLanguage('it')" value="it">IT</option>
<option ng-click="switchLanguage('fr')" value="fr">FR</option>
<option ng-click="switchLanguage('es')" value="es">ES</option>
</select>
但是由于某些原因,这些
ng-click
似乎没有调用指定的函数。我将它们全部都更改为按钮,这似乎很好用,但是我想要一个下拉列表,而不是按钮。谁能告诉我为什么这行不通?Controller 代码:
app.controller('langCtrl', function($translate, $location, $scope) {
$scope.switchLanguage = function (langKey) {
switch(langKey) {
case 'en':
$location.url('/#en');
break;
case 'de':
$location.url('/#de');
break;
case 'it':
$location.url('/#it');
break;
case 'fr':
$location.url('/#fr');
break;
case 'es':
$location.url('/#es');
break;
default:
$location.url('/#en');
}
$translate.use(langKey);
};
});
最佳答案
正确的方法是使用ng-model
angular.module('test', [])
.controller('langCtrl', function($scope, $location/*, $translate*/) {
$scope.switchLanguage = function() {
langKey = $scope.selected;
switch (langKey) {
case 'en':
alert('/#en');
//$location.url('/#en');
break;
case 'de':
alert('/#de');
//$location.url('/#de');
break;
case 'it':
alert('/#it');
//$location.url('/#it');
break;
case 'fr':
alert('/#fr');
//$location.url('/#fr');
break;
case 'es':
alert('/#es');
//$location.url('/#es');
break;
default:
alert('/#en');
//$location.url('/#en');
}
//$translate.use(langKey);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<select ng-app='test' ng-controller="langCtrl" ng-model="selected" ng-change="switchLanguage()">
<option value="en">EN</option>
<option value="de">DE</option>
<option value="it">IT</option>
<option value="fr">FR</option>
<option value="es">ES</option>
</select>
不知道为什么您的示例不起作用,看起来不错。