Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send the selected item from the angular-ui dropdown back to the angular controller

Using angular-ui, consider the following:

<div class="btn-group" dropdown is-open="status.isopen">
  <button type="button" class="btn btn-default btn-labeled dropdown-toggle fa fa-location-arrow" dropdown-toggle ng-disabled="disabled">
    Location: {{ loc }} <span class="caret"></span>
  </button>
  <ul class="dropdown-menu" role="menu">
    <li ng-repeat="choice in locations">
      <a>{{choice}}</a>
   </li>
  </ul>
</div>

The app:

var app = angular.module('Demo', ['ui.router', 'ui.bootstrap']);

app.controller('CrmCtrl', ['$scope', function ($scope) {
$scope.location = "Sutton Coldfield";
$scope.locations = [
    "Sutton Coldfield",
    "Coventry",
    "Redditch",
    "London",
    "Manchester",
    "Sheffield",
    "Dublin"
];
}]);

The aim is to get the selection location to change as the user selects a new location. i.e. the dropdown starts like 'Location: Sutton Coldfield' and should update to 'Location: Coventry' for instance. I might also want to use the value in a sidebar for example.

Example and Plunk: http://plnkr.co/edit/5giYygkYcVDJ6RvCKRMv?p=preview

To achieve this I can update $scope.loc but what I can't figure out is how to 'wire up' or 'push' the selected choice back to the controller.

I'm also looking for a best practice way of doing this as I am doing this primarily for my own personal learning.

I've seen some discussion about using ng-model on the A element, but it wasn't taken up.

like image 518
Mike Rouse Avatar asked Feb 01 '15 19:02

Mike Rouse


1 Answers

You would need to handle it manually, it is just a dropdown menu if you want to use it as a select. You could just set an ng-click on the repeated items of the dropdown.

<a ng-click="setChoice(choice)">{{choice}}</a>

and in your controller:

$scope.setChoice = function(data){
  $scope.loc = data;
 //Do somethign else..
}

Plnkr

like image 103
PSL Avatar answered Oct 26 '22 10:10

PSL