Angularjs 在切换的元素上设置焦点

Angularjs 在切换的元素上设置焦点,angularjs,Angularjs,我正在开发一个内联编辑功能(使用Angularjs),目前我的控制器中有以下功能: $scope.toggleEditor = function(){ $scope.editorEnabled = !$scope.editorEnabled; //toggle editor view //can't get this part to work as desired $timeout(function(){ angular.element("#email_editor").f

我正在开发一个内联编辑功能(使用Angularjs),目前我的控制器中有以下功能:

$scope.toggleEditor = function(){
  $scope.editorEnabled = !$scope.editorEnabled; //toggle editor view

  //can't get this part to work as desired
  $timeout(function(){
    angular.element("#email_editor").focus();
  },100);

}
HTML是:

<div ng-hide="editorEnabled">
  <span class="editable" ng-click="toggleEditor()">{{user.local.email}}</span>
</div>
<div ng-show="editorEnabled">
  <input type="text" id="email_editor" ng-model="user.local.email" ng-blur="toggleEditor()">
</div>

{{user.local.email}
这个想法是,当用户点击电子邮件地址时,它会显示一个包含电子邮件地址的文本框。这部分工作正常,但我希望文本框隐藏时,用户点击其他地方。因为我使用的是模糊上的
指令,所以文本框必须有焦点才能工作


问题一旦用户单击电子邮件地址,我如何设置文本框的焦点。请查看我的代码以了解我的尝试。

您最初的问题是因为控制器中没有注入
$timeout
。但是,您需要避免从控制器访问DOM。您可以将焦点活动移动到可重用指令,并保持控制器的简单

例如:-

app.controller('MainCtrl', function($scope) {
  $scope.toggleEditor = function(){
  $scope.editorEnabled = !$scope.editorEnabled; //toggle editor view
}
}).directive('focus', function(){
  return {
    scope: {
      set: "=" //Create a 2 way binding which you can bind it to editorEnabled
    },
    link:function(scope, elem){

      var unwatch = scope.$watch('set', function(v){
        if(v){
           elem.focus(); //focus on the element when value is set
        }
      });

      scope.$on('$destroy', function(){
         unwatch(); //Just safe cleanup of the watch.
      });
    }
  }
});
在您的输入集中:-

<input type="text" id="email_editor" ng-model="user.local.email" ng-blur="toggleEditor()" 
              focus set="editorEnabled">


在这里工作,您需要注入
$timeout
。另外,我希望您在安装之前已经加载了jquery。另一个提示。在Controllerooh bugger中访问DOM不是一个好主意!我忘了。thanksHow还有什么我可以设置焦点的吗我环顾四周,发现了这段代码。你可以创建一个指令,一个小的指令来实现这一点……像这样@tommyd456当然我也设置了一个演示。我要正确地标记它,因为它让我走上了正确的轨道(这非常有用)。