简体   繁体   中英

Angularjs: How to pre-select input text field on page load?

I have a simple text input field in my angular app which is prefilled with a default value. I want to preselect the text on page load.

Input field:

<input type="text" ng-model="city" class="form-control" select-on-load />

Directive:

weatherApp.directive('selectOnLoad', function () {
// Linker function
return function (scope, element, attrs) {
    element.bind('load', function () {
        this.select();
    });
};

});

But nothing happens.

The answers to this question suggest that there is no load event for input elements. However, maybe you could attach the handle once the view content has loaded ?

$scope.$on('$viewContentLoaded', function(){
    // Set a flag
  });

It isn't as neat as a directive, but it's the simplest alternative to my knowledge. The event sets a flag, the element uses an ng-focus depending on that flag, and your original directive can be updated to listen for focus, not load.


EDIT: I've done some searching, and can't find any ideas of a better alternative. It does feel a lot like a hack, so I welcome anyone with a better suggestion.

Super late but you can easily accomplish this using JS. Inside your controller...

Example...

Then inside your html id you have an input tag with a matching id

Easy peasy

Hope that helped!

Try this.

function selectOnLoadDirective() {
  return {
    link: function(scope, elem) {
      elem.focus().select();
    }
  };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM