【问题标题】:element.find() not working when using templateUrl in directive在指令中使用 templateUrl 时 element.find() 不起作用
【发布时间】:2014-07-03 16:22:21
【问题描述】:

我正在尝试通过表单上的自定义指令将焦点设置在输入字段上。在指令中使用模板属性时,这可以正常工作。但是当我通过templateUrl 将模板移动到单独的html 文件中时,element.find() 不再找到我的输入字段:

代码如下:

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.2.x" src="https://code.angularjs.org/1.2.16/angular.js" data-semver="1.2.16"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <form get-input-by-id="input2">
      <my-input id="input1"></my-input>
      <my-input id="input2"></my-input>
    </form>
  </body>

</html>

js:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
});

app.directive('getInputById', function() {
  return {
    link: function (scope, element, attrs) {
      //console.log(element);
      var toFocus = element.find('input');
      console.log(toFocus);
      toFocus[1].focus();
    }
  }
});

app.directive('myInput', function() {
  return {
    restrict: 'E',
    scope: {
      id: "@id",
    },
    // this is not working
    templateUrl: 'template.html',
    // this is working
    //template: '<div><input id="{{id}}"/></div>',
    link: function (scope, element, attrs) {
    }
  }
});

还有模板:

<div>
  <input id="{{id}}"/>
</div>

我添加了工作和不工作的 plunker:

This plunker is working.

This plunker is not working.

【问题讨论】:

标签: javascript angularjs


【解决方案1】:

问题是子指令在其模板下载之前不会呈现,因此父级的链接函数找不到任何input 元素(请阅读 cmets 中的另一个问题)。

两种方式都适用的一个选项是让子指令(无论何时呈现)询问父指令是否应该聚焦。

app.directive('getInputById', function() {
  return {
    scope: {
      getInputById: '@'
    },
    controller: function($scope) {
      this.isFocused = function(id) {
        return $scope.getInputById === id;
      }
    }
  }
});

app.directive('myInput', function() {
  return {
    restrict: 'E',
    require: '?^getInputById',
    scope: {
      id: "@id",
    },
    templateUrl: 'template.html',
    link: function (scope, element, attrs, ctrl) {
      if (ctrl && ctrl.isFocused(scope.id)) {
        var input = element.find('input')
        input[0].focus();
      }
    }
  }
});

这样,父指令可以更通用,并且不完全限于input 元素。每个不同的“可聚焦”控件都会询问父级并实现自己的焦点。

Working plunker

【讨论】:

  • 我按照您的建议实现了它,并且效果很好。我仍然想知道为什么 Angular 团队实现的模板与 templateUrl 不同。
  • 我玩弄了这个专注的东西,最终得到了this。我认为这是协作指令的一个很好的例子。当然,还有很多其他方法可以做同样的事情。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-07
  • 2017-10-28
  • 1970-01-01
相关资源
最近更新 更多