ng-init选择input元素的文本

时间:2017-05-02 11:06:29

标签: 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="edit"></div>
    <div ng-if="edit">
      <input type="text" select-text ng-model="name" size="30" placeholder="New Name" />
    </div>
  </div>
</div>

JS:

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();          
    }
  };
});

我无法在出现文本字段时调用焦点事件。

http://jsfiddle.net/pnnzb5sm/2/

2 个答案:

答案 0 :(得分:1)

我是使用UTF-16完成的,因此只要$watch更新,就会调用它

试试这个

&#13;
&#13;
edit
&#13;
&#13;
&#13;

答案 1 :(得分:0)

使用此

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

演示

&#13;
&#13;
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', function($scope) {
  $scope.name = "Johny";

}]);

myApp.directive('selectText', function($window) {
    return {
    require: 'ngModel', 
    link: function(scope, elem, attrs, ctrl) {
          elem.on('focus', function () {
                if (!$window.getSelection().toString()) {
                    // Required for mobile Safari
                    this.setSelectionRange(0, this.value.length)
                }
            });   
    }
  };
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<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 autofocus type="text" select-text ng-model="name" size="30" placeholder="New Name" />
    </div>
  </div>
</div>
&#13;
&#13;
&#13;