在ng-readonly = true之后,关注空ng模型数据

时间:2017-12-14 11:12:38

标签: javascript angularjs

我有一个表单输入。加载页面时,输入具有" ng-readonly = true"属性,它只显示数据。

当我双击(ng-dblclick)属性" ng-readonly"更改为 false ,我可以编辑输入。 尽管如此,它目前正在发挥作用。但是当数据 (ng-model =" school.fax")行数据为空,它确实执行了焦点,我需要点击输入来聚焦并开始写作。

当数据不为空时(ng-model =" school.fax"有值,从服务器API获取值)并且在这种情况下,它&& #39;正常工作

问题: 如何专注于空输入并开始编写而无需单击输入行?

代码:

HTML

<label>
    <input class="inputs"
        type="text"
        ng-readonly="!edit_school_fax"
        ng-dblclick="editSchoolFax(true)"
        ng-model="school.fax"/>
</label>

JS

$scope.editSchoolFax = function(edit) {
    $scope.edit_school_fax = edit;
};

FYI 我试试,它对我不起作用:

  • 添加&#34;自动对焦&#34;在输入内部 <input autofocus
  • 使用此解决方案的指令:LINK

2 个答案:

答案 0 :(得分:0)

添加自定义指令

 Dim ty as long
 Dim cday As Long
 Dim y As long
 Dim u As String
 y = Sheets.Count - 1
 u = Sheets(y).Name
 cday = Right(u, Len(u) - 3)
 cday = cday + 1
 Sheets.Add After:=Sheets(y)
 ty = Sheets(y + 1).Name
 Sheets(ty).Name = "Day" & cday 

答案 1 :(得分:0)

使用自定义指令向ngModelController添加focus方法:

app.directive("inputFormFocus", function() {
  return {
    require: "ngModel",
    link: postLink
  };
  function postLink (scope, elem, attrs, ngModel) {
    console.log("postLink");
    console.log(ngModel);
    ngModel.focus = function() {
      elem[0].focus();
    }
  }
})

用法

<form name="form1">
   <input input-form-focus
          name="fax" 
          class="inputs"
          type="text"
          ng-readonly="!edit_school_fax"
          ng-dblclick="editSchoolFax(true)"
          ng-model="school.fax"/>
</form>
$scope.form1.fax.focus();

The DEMO

angular.module("app",[])
.controller("ctrl",function($scope){
  $scope.editSchoolFax = function(edit) {
    $scope.edit_school_fax = edit;
  };
  $scope.school = { fax: "555-100-1234" };
  $scope.faxFocus = function() {
    $scope.edit_school_fax = true;
    $scope.form1.fax.focus();
  };
})
.directive("inputFormFocus", function() {
  return {
    require: "ngModel",
    link: postLink
  };
  function postLink (scope, elem, attrs, ngModel) {
    ngModel.focus = function() {
      console.log(attrs.name + " focus");
      elem[0].focus();
    }
  }
})
<script src="//unpkg.com/angular/angular.js"></script>
  <body ng-app="app" ng-controller="ctrl">
    <form name="form1">
       <input input-form-focus
              name="fax" 
              class="inputs"
              type="text"
              ng-readonly="!edit_school_fax"
              ng-dblclick="editSchoolFax(true)"
              ng-model="school.fax"/>
    </form>
    <button ng-click="faxFocus()">Focus and Edit</button>
  </body>