I am using AngularJS to implement web application.
You can find an URL text filed in the web page.
The requirement is the width of the URL text field will resize based on the text length which key in by end user.
How to do it?
How-To
You can make good use of ng-keyup and ng-style to fulfill this requirement.
Using ng-keyup to calculate the length of text and using ng-style to set width at the same time.
The HTML code snippet looks like:
1 2 3 4 5 6 7 8 | <div class="row"> <div class="form-group col-sm-3"> <!- ignore --> <label for="url" class="control-label label-width-5">URL</label> <input type="text" id="url" name="url" class="form-control" data-ng-model="model.url" data-ng-keyup="keyInUrl()" data-ng-style="{'width':urlWidth}"> </div> </div> |
The JavaScript code snippet are the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | // set the initial value for url width $scope.urlWidth = 200; // calculate width at runtime $scope.keyInUrl = function() { var url = $scope.model.url; if (!isEmptyOrUndefined($scope.model.url)){ var width = ((url.length + 1) * 9); console.log('width = ' + width); if(width > 200) { $scope.urlWidth = width; } else { $scope.urlWidth = 200; } } } |
Demo:
No comments:
Post a Comment