简体   繁体   English

Angularjs:如何在页面加载时预先选择输入文本字段?

[英]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. 对这些问题的答案这个问题表明,没有load的输入元素的事件。 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. 该事件设置一个标志,该元素根据该标志使用ng-focus ,并且您的原始指令可以更新以侦听焦点,而不是加载。


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. 太晚了,但是您可以使用JS轻松完成此操作。 Inside your controller... 在控制器内部...

Example... 例...

Then inside your html id you have an input tag with a matching id 然后在您的html ID中,您有一个带有匹配ID的输入标签

Easy peasy 十分简单

Hope that helped! 希望能有所帮助!

Try this. 尝试这个。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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