Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular using ng-click in a select tag

I want a dropdown list to change the language my site is displayed in, so I currently have:

<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>

However for some reasons these ng-clicks don't seem to be calling the specified function. I changed them all to buttons, and that seemed to work fine, but I want a dropdown list, not buttons. Can anyone tell me why this doesn't work?

Controller code:

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);
  };
});
like image 348
user2412643 Avatar asked Aug 01 '26 02:08

user2412643


1 Answers

A proper way to do this would be using 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>

Not sure why your example doesn't work though, it looks fine.

like image 194
Icycool Avatar answered Aug 02 '26 16:08

Icycool