AngularJS-正在检索已评估的属性

AngularJS - retrieving evaluated attribute

本文关键字:评估 属性 检索 AngularJS-      更新时间:2023-09-26

我有一个基本的表单输入指令,它根据名称设置一些表单元素:

angular.module('myApp').directive('formInput', function () {
  return {
    restrict: 'A',
    require: '^form',
    link: function (scope, element, attributes, form) {
      var input, name;
      input = element[0].querySelector('input, textarea, select');
      name = input.getAttribute('name');
      // ...
      // do stuff with input, name, form etc.
    }
  };
});

在我的HTML中,我做了一些简单的DOM设置,它就完成了任务。

<div form-input>
  <input type="text" name="myElement"/>
</div>

当我开始使用动态名称时,问题就来了,即

<div form-input>
  <input type="text" name="{{ getDynamicName(element) }}"/>
</div>

在进入我的指令之前,不会评估动态名称。有办法解决这个问题吗?

附言:考虑到指令的装饰性,我不喜欢使用隔离范围。

使用0ms的$timeout服务在内部元素链接后运行代码:

// Note that $timeout is now injected to the directive
    angular.module('myApp', []).directive('formInput', function ($timeout) {
        return {
            restrict: 'A',
            //require: '^form',
            link: function (scope, element, attributes, form) {
                $timeout(function() {
                        var input, name;
                        input = element[0].querySelector('input, textarea, select');
                        name = input.getAttribute('name');
                        alert(name);
                }, 0);
                // ...
                // do stuff with input, name, form etc.
            }
        };
    });

JSFiddle