Search code examples
angularjsdropdownbox

add event onClick to the last element of a dropdown


Let's say I have a dropdown list and I want to add an onClick event to the last element of the list, as e.g:

  • London
  • Paris
  • Milan
  • Add New City +

ng-change directive just helps me if I have more than one element in the dropdown, otherwise if I have a list like this (with only one element):

  • Add New City +

I will never be able to set the onClick event to the only item, since it never changes the value of the combo box.

UPDATE

<select ng-model="customer.selectedCity"  ng-options="opt as opt.name for opt in customer.cityOptions"
  ng-init="model="customer.selectedCity"   = customer.cityOptions[0]"
  ng-change="onCustomerCitySelected(customer)" ></select>

Solution

  • You can achieve this without using ng-change at all. Consider the following:

    HTML template

    <select ng-model="selectedIndex"
            ng-options="index as name for (index, name) in menu"> 
    </select> 
    

    JavaScript

    app.controller('SelectCtrl', function($scope) {
      $scope.menu = ['London','Paris','Milan','Add new city+'];
    
      $scope.$watch('selectedIndex', function(val) {
        $scope.selectedCity = $scope.menu[val];      
    
        if (val == $scope.menu.length - 1) {
          $scope.addNewCity();
          $scope.selectedIndex = $scope.selectedCity = null;
        }
      });
    
      $scope.addNewCity = function() {
        alert('Add city from select');
      };
    });
    

    You could also think about using ui-bootstrap dropdown.

    HTML template

    <div class="btn-group" dropdown>
      <button type="button" 
              class="btn btn-primary">{{ vm.selectedCity || 'Not selected' }}
      </button>
      <button type="button" 
              class="btn btn-primary dropdown-toggle" 
              dropdown-toggle>
        <span class="caret"></span>
      </button>
      <ul class="dropdown-menu" role="menu">
        <li ng-repeat="item in vm.menu">
          <a ng-if="!$last" href="#" 
             ng-bind="item"
             ng-click="vm.selectedCity = item"></a> 
          <a ng-if="$last" href="#" 
             ng-bind="item"
             ng-click="vm.addNewCity()"></a>
        </li>
      </ul>
    </div>
    

    JavaScript

    app.controller('DropdownCtrl', function() {
      var vm = this;
      vm.menu = ['London','Paris','Milan','Add new city+'];
    
      vm.addNewCity = function() {
        alert('Add city from dropdown');
        vm.selectedCity = null; 
      };
    });
    

    Examples above would result in something like this

    enter image description here

    Related plunker with all teh codes here http://plnkr.co/edit/szA1pt