2013-08-30 36 views
5

簡單的焦點時,不會在角對焦功能沒有在角

<div class="search pull-right tab-{{ showDetails2 }}" data-ng-click="showDetails2 = !showDetails2; showDetails = false; showDetails1 = false;searchFocus();"> 

HTML

<input type="text" data-ng-model="model.fedSearchTerm" 
        placeholder="New Search" required class="span12 fedsearch-box" /> 

我的函數工作

$scope.searchFocus = function() { 
      $('.fedsearch-box').focus(); 
     }; 
+0

http://stackoverflow.com/questions/14833326/how-to-set-focus-in-angularjs看馬克的答案在這裏。 –

回答

9

這裏是一個更強大的實現,它工作得非常好:

myApp.directive('focusMe', function() { 
    return { 
     link: function(scope, element, attrs) { 
      scope.$watch(attrs.focusMe, function(value) { 
       if(value === true) { 
        element[0].focus(); 
        element[0].select(); 
       } 
      }); 
     } 
    }; 
}); 


<input type="text" ng-model="stuff.name" focus-me="true" /> 
+1

這確實工作得很好。你能否解釋爲什麼$ watch需要包裝焦點並選擇?我嘗試刪除$ watch,當然如果沒有它,它就無法工作。 –

1

你可以寫一個指令,用於此目的的像;

myApp.directive('focus', function() { 
    return function (scope, element, attrs) { 
      element.focus(); 
    } 
}); 

而在你的HTML中;

<input type="text" data-ng-model="model.fedSearchTerm" 
        placeholder="New Search" required focus /> 
9

我遇到了同樣的問題。通過將焦點命令放在$ timeout中解決它。確保您在.controller函數中傳遞$ timeout參數。

$timeout(function() { $('.fedsearch-box').focus(); }); 
+0

對我來說很好,並且解決了這個問題。 – Habeeb

+0

不錯,對我也很好 –