Angularjs ng init选择输入元素的文本

Angularjs ng init选择输入元素的文本,angularjs,angularjs-directive,Angularjs,Angularjs Directive,每当用户选中/取消选中复选框时,我就设置var edit=true/false。我有一个输入字段,在编辑为真/假时显示/消失。我要做的是在文本字段出现时选择输入字段的文本值 HTML: <div ng-app="myApp"> <div ng-controller="MyCtrl"> <input type="checkbox" ng-model="edit" ng-init="edit = true"> <div ng-bind="

每当用户选中/取消选中复选框时,我就设置
var edit=true/false
。我有一个输入字段,在编辑为真/假时显示/消失。我要做的是在文本字段出现时选择输入字段的文本值

HTML:

<div ng-app="myApp">
  <div ng-controller="MyCtrl">
    <input type="checkbox" ng-model="edit" ng-init="edit = true">
    <div ng-bind="edit"></div>
    <div ng-if="edit">
      <input type="text" select-text ng-model="name" size="30" placeholder="New Name" />
    </div>
  </div>
</div>
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', function($scope) {
  $scope.name = "Johny";

}]);

myApp.directive('selectText', function() {
    return {
    require: 'ngModel',
    link: function(scope, elem, attrs, ctrl) {
        elem.bind('focus', function() {
            $(elem).select();
        });
      $(elem).focus();          
    }
  };
});
无论何时出现,我都很难调用textfield的焦点事件

使用这个

 if (!$window.getSelection().toString()) {
     this.setSelectionRange(0, this.value.length)
 }
演示

var myApp=angular.module('myApp',[]);
控制器('MyCtrl',['$scope',函数($scope){
$scope.name=“Johny”;
}]);
myApp.directive('selectText',函数($window){
返回{
要求:'ngModel',
链接:函数(范围、元素、属性、ctrl){
要素on('焦点',功能(){
如果(!$window.getSelection().toString()){
//移动狩猎需要
this.setSelectionRange(0,this.value.length)
}
});   
}
};
});

我是用
$watch
来做的,所以无论何时
编辑
更新,它都会调用它

试试这个


var myApp=angular.module('myApp',[]);
控制器('MyCtrl',['$scope',函数($scope){
$scope.name=“Johny”;
}]);
myApp.directive('selectText',function(){
返回{
要求:'ngModel',
链接:函数(范围、元素、属性、ctrl){
元素绑定('focus',function(){
$(elem.select();
});
范围.$watch(“编辑”),函数(newValue,oldValue){
//当数据更改时,将调用此函数。
$(elem.select();
});
$(elem.focus();
}
};
});

$(elem).focus()已聚焦该元素。据我所知,没有
select
event它的工作原理和我的小提琴一样,不是吗?每当选中复选框时,我希望文本字段自动恢复焦点。