2016-03-28 68 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屬性定義了它的條件。

希望它有幫助。