【问题标题】:Angularjs directives access attributes to container elementsAngularjs 指令访问容器元素的属性
【发布时间】:2013-12-08 00:47:55
【问题描述】:

我正在尝试制作一个自动将标签添加到输入字段的指令,所以我想要实现的是:

<!-- angular -->
<label-input label="some label:" id="some-random-id">
  <input type="text" maxlength="5" />
</label-input>

并将其转换为:

<!-- html -->
<label for="some-random-id">
  some label: <input id="some-random-id" type="text" maxlength="5" />
</label>

我已经走了这么远,但我不明白你应该如何修改通过嵌入添加的元素,或者你应该如何修改?

app.directive('labelInput', function () {
  return {
    restrict: 'E',
    transclude: true,
    scope: {
      id: '@',
      label: '@',
    },
    template: '<label for="{{id}}">{{label}}</label><span ng-transclude></span>',
  };
});

我主要担心的是我不想写两次 id,最好是,如果 id 没有传递,让它自动生成,也就是:

<label-input><input type="text" /></label-input>

转换为:

<label for="some-random-id-1231231"></label><input type="text" id="some-random-id-1231231" />

【问题讨论】:

    标签: javascript angularjs angularjs-directive


    【解决方案1】:

    您可以在指令中添加一个链接函数,您可以(并且应该)在其中修改和/或控制指令的行为及其 DOM 表示。欲了解更多信息,请访问the docs on directives

    给定以下标记:

    <body ng-app="myModule">
        <div>
            <label-input label="some label with a given id:" id="some-random-id">
                  <input type="text" maxlength="5" />
            </label-input>
        </div>
        <div>
            <label-input label="another label with a random id:">
                  <input type="text" maxlength="5" />
            </label-input>
        </div>
    </body> 
    

    根据您的需要运行的指令可能如下所示:

    var app = angular.module('myModule', [])
    app.directive('labelInput', function () {
      return {
        restrict: 'E',
        transclude: true,
        scope: {
          id: '@',
          label: '@',
        },
        template: '<label for="{{id}}">{{label}}</label><span ng-transclude></span>',
        link: function (scope, element, attrs) {
            scope.id = attrs.id || 'input-id-'+ new Date().getTime().toString()
            element.find('input').attr('id', scope.id);
        }
      }}); 
    

    小提琴:http://jsfiddle.net/uz76h/

    请注意,id 生成远非防弹。

    编辑:根据下面评论中的要求进行扩展

    没有嵌入:

     app.directive('labelInput', function () {
      return {
        restrict: 'E',
        scope: {
          id: '@',
          label: '@',
        },
        link: function (scope, element, attrs) {
            scope.id = attrs.id || 'input-id-'+ new Date().getTime().toString()
            element.prepend('<label for="'+scope.id+'">'+scope.label+'</label>');            
            element.find('input').attr('id', scope.id)
        }
      }}); 
    

    【讨论】:

    • 很好的答案!还有一个简短的问题,你知道我如何绕过添加 而只是告诉 angular 在标签标签之后附加内容吗?
    • 这正是ng-transclude 指令的用途。但是您可以通过简单地通过angular.element 预先添加标签标签来省略嵌入标签。更新了我的答案。
    猜你喜欢
    • 2012-08-08
    • 1970-01-01
    • 1970-01-01
    • 2016-10-26
    • 2015-06-06
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多