一旦数据加载(在这种情况下通过$ resource),是否可以通过控制器设置输入字段的焦点?
输入通过ng-show隐藏,直到从API返回数据,但我找不到将注意力设置在输入上的方法 . 我知道输入的ng-model名称和输入名称,这意味着我可以通过jQuery来完成它,但我宁愿在可能的情况下使用AngularJS方式 .
我发生在我的情况下)或者只是不工作 .非常感谢任何提示 .
这是一个可能适合您的简单指令
<input focus-on="!!myResourceData" /> .directive('focusOn',function($timeout) { return { restrict : 'A', link : function($scope,$element,$attr) { $scope.$watch($attr.focusOn,function(_focusVal) { $timeout(function() { _focusVal ? $element[0].focus() : $element[0].blur(); }); }); } } })
我已经扩展了使用angular的 ng-show 和 ng-hide 的答案
ng-show
ng-hide
app.directive('focusOnShow', function($timeout) { return { restrict: 'A', link: function($scope, $element, $attr) { if ($attr.ngShow){ $scope.$watch($attr.ngShow, function(newValue){ if(newValue){ $timeout(function(){ $element[0].focus(); }, 0); } }) } if ($attr.ngHide){ $scope.$watch($attr.ngHide, function(newValue){ if(!newValue){ $timeout(function(){ $element[0].focus(); }, 0); } }) } } }; })
您只需要添加属性 focus-on-show
focus-on-show
<input type="text" ng-show="editing" focus-on-show />
基于koolunix的答案,如果你只是想要聚焦输入元素,那么找到第一个输入元素也是有用的,该元素是具有focus-on指令的元素的子元素 .
这在外部库使用指令和模板抽象输入元素的情况下很有用 .
.directive('focusOn', function ($timeout) { return { restrict: 'A', priority: -100, link: function ($scope, $element, $attr) { $scope.$watch($attr.focusOn, function (_focusVal) { $timeout( function () { var inputElement = $element.is('input') ? $element : $element.find('input'); _focusVal ? inputElement.focus() : inputElement.blur(); }); } ); } }; });
你必须在你的控制器中使用超时才能在此之前呈现它是一个类似的例子,默认情况下隐藏了一个搜索框
HTML:
<input ng-show="vm.isActive" id="searchInputBox" ></input> <input type="button" ng-click="vm.toggleActiveInactive();">
控制器:
vm.isActive=false; vm.toggleActiveInactive=toggleActiveInactive; // vm= viewmodel function toggleActiveInactive() { if(vm.isActive==true){ vm.isActive=false; }else{ vm.isActive=true; $timeout(function(){ document.getElementById('searchBoxInput').focus() }, 10 ); } }
4 回答
这是一个可能适合您的简单指令
我已经扩展了使用angular的
ng-show
和ng-hide
的答案您只需要添加属性
focus-on-show
基于koolunix的答案,如果你只是想要聚焦输入元素,那么找到第一个输入元素也是有用的,该元素是具有focus-on指令的元素的子元素 .
这在外部库使用指令和模板抽象输入元素的情况下很有用 .
你必须在你的控制器中使用超时才能在此之前呈现它是一个类似的例子,默认情况下隐藏了一个搜索框
HTML:
控制器: