0

Based on this stackoverflow question here: How to set focus on input field?

I'm using the same Directive focuseMe named focusSearch in my example here: http://plnkr.co/edit/tdSxya?p=preview

However the input does not automatically gain focus as soon as the input is revealed.

  • Step 1: Click the Show Search button
  • Step 2: The input should automatically get focused
Show Search
<!-- <div class="search-input container-fluid"> -->
<div class="search-input" ng-show="showingSearchInput">
    <input type="text"
           class="form-control"
           placeholder="Search"
           ng-model="vh.searchInput"
           ng-click="vh.searchPop($event)"
           focus-search="showingSearchInput">

    <div class="close-x-sml" ng-click="hideSearch()">(x)</div>
</div>

AngularJS code:

angular.module('app', [])

.directive('focusSearch', ['$timeout', '$parse', function($timeout, $parse) {
  return {
    link: function(scope, element, attrs) {
      var model = $parse(attrs.focusMe);
      scope.$watch(model, function(value) {
        console.log('value=',value);
        if (value === true) { 
          $timeout(function() {
            element[0].focus();
          });
        }
      });
      // to address @blesh's comment, set attribute value to 'false'
      // on blur event:
      element.bind('blur', function() {
        console.log('blur');
        scope.$apply(model.assign(scope, false));
      });
    }
  }
}])

.controller('sidebar',
['$scope',
 '$rootScope',
 '$timeout',
 function($scope,
          $rootScope,
          $timeout) {

var vs = $scope;

$scope.clickedSearch = function() {
  vs.showingSearchInput = true;
}

$scope.hideSearch = function() {
  vs.showingSearchInput = false;
}

}]);
Community
  • 1
  • 1
Leon Gaban
  • 36,509
  • 115
  • 332
  • 529

2 Answers2

2

That's because you are parsing the value of focusMe, when your directive name is focusSearch. Change the $parse argument to attrs.focusSearch, and your directive works

var model = $parse(attrs.focusSearch);
Patrick
  • 17,669
  • 6
  • 70
  • 85
0

Just realized he had recently updated his original question with an update to his Directive. This works now:

https://stackoverflow.com/a/14837021/168738

app.directive('focusMe', function($timeout) {
  return {
    scope: { trigger: '=focusMe' },
    link: function(scope, element) {
      scope.$watch('trigger', function(value) {
        if(value === true) { 
          //console.log('trigger',value);
          //$timeout(function() {
            element[0].focus();
            scope.trigger = false;
          //});
        }
      });
    }
  };
});
Community
  • 1
  • 1
Leon Gaban
  • 36,509
  • 115
  • 332
  • 529