Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manually toggle angular-ui-select dropdown

I'm using AngularUI's ui-select to create several multiselects on a page. I need to be able to open the dropdown list when a user clicks on a button on the page.

I've tried using jQuery's .click() and .toggle('click') on the element, but these result in a $apply already in progress error when called by in the button's ng-click function. They work when called from Chrome's console though. The function in ng-click doesn't do anything besides simulating another click.

.focus() doesn't do anything, besides focusing the input.

I also reluctantly tried a nasty hack, where I used the select's ng-init to store it's controller to a scope the button has access to, and then using the controller's toggle() and activate() methods. This gave focus to the input, but the associated dropdown list wont open.

How can I toggle the dropdown manually, from outside the ui-select element's context?

Here's a Plunker you can play with.

like image 929
Schlaus Avatar asked Nov 04 '14 17:11

Schlaus


2 Answers

I have tried and could be achieved by directive method. working fiddle

angular
  .module('myApp', [
    'ngSanitize',
    'ui.select'
  ])
  .controller('testController', function ($scope) {
    $scope.things = ['item1', 'item2'];
    $scope.clickOnInput = function() {
      //jQuery('#searchBarArea').click();
    };
  })
  .directive('openMenuByClick', function ($timeout) {
    return {
        link: function (scope, element, attrs) {
               element.bind('click', function () {

                 $timeout(function () {
                     $("#"+attrs.openMenuByClick).find('input').click();
                });


            });
        }
    };
});

Add this attribute directive to your button

<button id="btn" open-menu-by-click="searchBarArea">Click me</button>
like image 194
Asik Avatar answered Oct 13 '22 00:10

Asik


I recommend to use the $select service in a custom directive instead of trying to hack your way around by clicking programmatically.

You can then access ui-select's built in actions like
$select.toggle() for toggling the dropdown
$select.activate() for opening and
select.close() for closing the dropdown.

myModule.directive('myUiSelect', function() {
  return {
    require: 'uiSelect',
    link: function(scope, element, attrs, $select) {
      $select.activate(); // call this by an event handler
    }
  };
});

And in your template

<ui-select my-ui-select>
  ...
</ui-select>

See reference: https://github.com/angular-ui/ui-select/wiki/Accessing-$select

like image 21
David Salamon Avatar answered Oct 12 '22 23:10

David Salamon