0

I am using angular implementation of ui-select. It works fine but element[0].focus() does not work with it. To explain it further, I have following directive to set focus on ui-select

var focusIf = function ($timeout, $parse) {
    return {
        require: "ngModel",
        //scope: {
        //    updateFrom: "&"
        //},
        link: function (scope, element, attrs, ngModel) {
            console.log("in focus if");
            var focusChecker = $parse(attrs.focusIf);
            scope.$watch(function () {
                return focusChecker(scope);
            }, function (newVal, oldVal) {
                console.log("new val", newVal);
                console.log("old val", oldVal);
                if (newVal === true && !oldVal) {
                    console.log('inside condition');
                    console.log("element", element[0]);
                    $timeout(function () {
                        element[0].focus();
                    });


                }
            })

        }
    };
};
app.directive("focusIf", focusIf);

I am using this directive on ui-select like

<ui-select name="supplierId" data-focus-if="isSupplierInvoice()" ng-model="transaction.SupplierInvoice.supplierId" theme="select2" data-ng-show="isSupplierInvoice()" data-ng-required="isSupplierInvoice()" data-ng-disabled="disabled" style="width:100%;">
                <ui-select-match placeholder="Select a supplier or search...">{{$select.selected.Name}}</ui-select-match>
                <ui-select-choices repeat="supplier.ID as supplier in suppliers | propsFilter: {Name: $select.search, IdentityNumber: $select.search}">
                    <div ng-bind-html="supplier.Name | highlight: $select.search"></div>
                    <small>
                        Identity Number: <span ng-bind-html="''+supplier.IdentityNumber | highlight: $select.search"></span>

                    </small>
                </ui-select-choices>

            </ui-select>

the isSupplierInvoice() becomes true on change event of a regular html drop down. But focus does not get to ui-select even though the function returns true. I have verified the directive, it works fine with regular html inputs.

halfer
  • 19,824
  • 17
  • 99
  • 186
Muhammad Adeel Zahid
  • 17,474
  • 14
  • 90
  • 155

1 Answers1

0

I am not sure if you used the timeout like below. Try wrapping the code in a timeout this way.

 function safeFocus() {
          $timeout(function () {
              element[0].focus();
          }, 0);
      }
abhinav3414
  • 946
  • 3
  • 9
  • 31