我想要一个下拉列表来更改我的网站显示的语言,所以我目前有:
<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
似乎没有调用指定的函数。我将它们全部更改为按钮,这似乎工作正常,但我想要一个下拉列表,而不是按钮。谁能告诉我为什么这不起作用?
控制器代码:
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);
};
});
答案 0 :(得分:10)
执行此操作的正确方法是使用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);
}
});
&#13;
<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>
&#13;
不确定为什么你的例子不起作用,看起来很好。
答案 1 :(得分:0)
您可以使用ng-model
和ng-change
试试这个
<div ng-controller="langCtrl">
<select ng-change="switchLanguage(ModelName)" ng-model="ModelName">
<option value="en">EN</option>
<option value="de">DE</option>
<option value="it">IT</option>
<option value="fr">FR</option>
<option value="es">ES</button>
</select>
</div>
控制器
$scope.switchLanguage = function(ModelName)
{
var seletedValue = ModelName;
}