Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular ui-sref on dropdown not working

Tags:

angularjs

I have an angular app with routing. I have a dropdown select defined as follows:

<select class="form-control" id="transactiontype" ng-model="tt">
    <option><a ui-sref="cash">Cash</a></option>
    <option><a ui-sref="cheque">Cheque</a></option>
    <option><a ui-sref="debitcard">Debit</a></option>
    <option><a ui-sref="creditcard">Credit</a></option>
</select>

When i select one of the dropdowns, somehow it is not loading the view i am referencing. Where am i going wrong? I also tried this:

<option ui-sref="creditcard">Credit</option>
like image 962
Abhishek Avatar asked Mar 17 '23 16:03

Abhishek


2 Answers

I'm pretty sure it's because the a tags won't work inside the select - option tags.

As per this SO question: using href link inside option tag

Try writing a function that will redirect the page and trigger it based on the select change or maybe your model change, whatever it best for your program.

something like:

<select class="form-control" id="transactiontype" ng-model="tt" ng-change="locationChangeFunction()">
...
</select>

Your controller might look like:

angular.module('myApp')
.controller('myController', ['$scope', '$state', function ($scope, $state){

    $scope.locationChangeFunction = function(){
         $state.go($scope.tt);
    }
}]);

EDIT

Use a combination of both solutions (credit to Hieu TB):

<select class="form-control" id="transactiontype" ng-model="tt" ng-options="opt.value as opt.label for opt in options" ng-change="locationChangeFunction()"></select>

ng-change will wait for the model change, which will change the DOM, which will trigger the change, now you're not running a resource consuming $watch function

like image 153
Likwid_T Avatar answered Mar 28 '23 09:03

Likwid_T


consider using ng-options instead:

myApp.controller('MainController', ['$scope', '$state', function($scope, $state) {    
$scope.options = [
  { label: 'Cash', value: 'cash' },
  { label: 'Cheque', value: 'cheque' },
  { label: 'Debit', value: 'debit' },
  { label: 'Credit', value: 'credit' }
];
$scope.$watch('tt', function(value) {
  if(value) {
    $state.go(value);
  }
});
}]);

HTML:

<div ng-controller="MainController">
  <select class="form-control" id="transactiontype" ng-model="tt" ng-options="opt.value as opt.label for opt in options">
  </select>
</div>

EDIT: Agree with what @Likwid_T said, I think ng-change is the best choice to detect the change in select tag. I just forgot about it at that moment. So please refer to his answer too. Good day.

like image 27
Hieu TB Avatar answered Mar 28 '23 07:03

Hieu TB