2016-03-28 69 views
11

当我环绕我的inputng-if,隐藏后显示autofocus属性不生效输入自动对焦:AngularJS - 与NG-如果不工作

下面是代码:

<!DOCTYPE html> 
<html ng-app> 

    <head> 
    <script data-require="[email protected]" data-semver="1.5.0" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.js"></script> 
    <link rel="stylesheet" href="style.css" /> 
    <script src="script.js"></script> 
    </head> 

    <body ng-init="view={}; view.show = true"> 
    <button ng-click="view.show = !view.show">{{view.show ? "hide" : "show"}}</button> 
    <div ng-if="view.show"> 
     <input autofocus /> 
    </div> 
    </body> 
</html> 

而且这里是plunker: http://plnkr.co/edit/k7tb3xw5AsBYrhdlr3bA?p=preview

只需点击隐藏,然后在显示,你会看到自动对焦不工作!

上的首秀唯一的工作,在FFIE它不工作了!

回答

15

问题属性autofocus不是Angular指令。这是一个browser supported specification of the <input> element。如果您希望在多个浏览器中按预期工作,并且每次单击隐藏/显示时都会自动对焦,则需要制定指令。

我采取了这个指令马上Github Gist,贷款mlynch为构建这个指令。

继承人申请

angular 
 
    .module('App', [ 
 
     'utils.autofocus', 
 
    ]); 
 
    
 
/** 
 
* the HTML5 autofocus property can be finicky when it comes to dynamically loaded 
 
* templates and such with AngularJS. Use this simple directive to 
 
* tame this beast once and for all. 
 
* 
 
* Usage: 
 
* <input type="text" autofocus> 
 
* 
 
* License: MIT 
 
*/ 
 
angular.module('utils.autofocus', []) 
 

 
.directive('autofocus', ['$timeout', function($timeout) { 
 
    return { 
 
    restrict: 'A', 
 
    link : function($scope, $element) { 
 
     $timeout(function() { 
 
     $element[0].focus(); 
 
     }); 
 
    } 
 
    } 
 
}]);
<!DOCTYPE html> 
 
<html ng-app="App"> 
 

 
    <head ng-init="view={}; view.show = true"> 
 
    <script data-require="[email protected]" data-semver="1.5.0" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.js"></script> 
 
    <link rel="stylesheet" href="style.css" /> 
 
    </head> 
 

 
    <body> 
 
    <button ng-click="view.show = !view.show">{{view.show ? "hide" : "show"}}</button> 
 
    </body> 
 
    
 
    <div ng-if="view.show"> 
 
    <input autofocus /> 
 
    </div> 
 

 
    <script src="script.js"></script> 
 
</html>

+1

我想添加一个东西到你的解决方案 - 前缀的指令。像在'directive(...)'中注册'abcAutofocus'一样在HTML模板中使用'abc-autofocus'以避免混淆使用哪种解决方案 - 纯HTML或Angular指令。 –

+0

Greaaaaaat解决方案。谢谢 –

-1

首先,你必须将div和它的内容包裹在body元素中。你在外面。请更正它。

输入元素不应为空,有时可能无法工作。请添加一些更多的属性,如名称type =“text”或适当的。 这是html5功能,应该从<!DOCTYPE html>

请注意:The autofocus attribute of the input tag is not supported in Internet Explorer 9 and earlier versions.visit here for more details

+0

修正了演示的工作示例,这不是问题,在IE11测试。你可以测试它。它不起作用 – cheziHoyzer

2

您可以使用一个指令这一点。 Plunker Demo

angular.module('myApp', []).directive('focusMe', function($timeout) { 
    return { 
     scope: { 
      focusMeIf:"=" 
     }, 
     link: function (scope, element, attrs) { 
      if (scope.focusMeIf===undefined || scope.focusMeIf) { 
       $timeout(function() { element[0].focus(); }); 
      } 
     } 
    }; 
}); 

你也可以在它focus-me-if属性定义了它的条件。

希望它有帮助。