Franz Noel
Franz Noel

Reputation: 1900

Resizing input size on focus and blur in angularjs

I'm trying to change the input size from 20 to 100 each time it ng-focus. Then, when it ng-blur, it should convert from 100 to 20. Here is my html code:

<div ng-controller="MenuCtrl" class="navbar-collapse collapse bs-navbar-collapse navbar-ex1-collapse">
  <input type="text" class="form-control" ng-blur="{[{ change_text_width() }]}" ng-focus="{[{ change_text_width() }]}" size="{[{search_text_width}]}" placeholder="Search">
</div>

Before my angular module, I put a parent module:

var JobMaps = angular.module('JobMaps', ['MenuCtrl']); 

Here is my angular code:

var MenuCtrl = angular.module('MenuCtrl',[]);
MenuCtrl.controller = angular.module('MenuCtrl',function($scope) {
  $scope.search_text_width = 20;
  $scope.change_text_width = function() {
    if ($scope.search_text_width==20) {
      $scope.search_text_width = 100;
      //alert($scope.search_text_width);
    } else {
      $scope.search_text_width = 20;
      //alert($scope.search_text_width);
    }
  }
});

Observation:

  1. I tried to alert it, and it seems like it runs several times.
  2. I think it may be converting from 20 to 100 and 100 to 20 back so fast, I could not see it... Well, it could be a possibility because of several alerts that popup.

Upvotes: 1

Views: 2518

Answers (2)

Franz Noel
Franz Noel

Reputation: 1900

I changed the attribute size because width can affect the responsiveness when using Bootstrap.

MenuCtrl.directive('changeSize', function () {
  return {
    restrict: 'A',
    link: function($scope, $element, $attributes) {
      var onFocusSize = $attributes['changeSize'] || $element.attr('size');
      var onBlurSize = $element.attr('size');
      $element.focus(function() { $element.attr('size',onFocusSize); });
      $element.blur(function() { $element.attr('size',onBlurSize); });
    }
  }
});

Upvotes: 2

tschiela
tschiela

Reputation: 5271

In the Angular world you use directives for DOM manipulation. One advantage is that you can reuse the directives without much extra code and seperate the UI stuff from the controller. I created a plunker for the resizing input: Plunker

Upvotes: 6

Related Questions