javascript - AngularJS - 检索评估的属性

标签 javascript angularjs angularjs-directive

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

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

关于javascript - AngularJS - 检索评估的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33887956/

相关文章:

javascript - 在 Meteor 中缩短收集字段以进入

javascript - 带循环克隆的 Angular Owl 旋转木马超出范围

javascript - Angular : Directive Isolated Scope Undefined

angularjs - 是否可以使用范围:true从Angular Directive更新父范围。

javascript - 负载包括在现有模型上

javascript - Material-UI:以编程方式触发悬停效果

javascript - Babel 7 和 preset-es2015 不能一起工作

angularjs 链式淡入/淡出过渡

javascript - 期望 toNotBe() 未定义不是函数

javascript - AngularJS - 范围在链接函数中重置,我做错了什么?