简体   繁体   English

如何在指令中向子元素添加属性

[英]How to add attributes to child element in directive

I have the following plunkr: 我有以下plunkr:

http://plnkr.co/edit/M1uwZxZP7sXp5sPw7pxf?p=preview http://plnkr.co/edit/M1uwZxZP7sXp5sPw7pxf?p=preview

What I want to do is: I'd like to build an angular code to generate inputs automatically inside a form, given a json with it's description EXAMPLE: 我想做的是:我想构建一个角度代码来自动生成表单内的输入,给定一个带有描述示例的json:

{'name': 'username', 'description': ['text', 'maxlength=16', 'required']}

To do so, I'm using a custom directive that appends input to the tag 为此,我使用了一个自定义指令,该指令将输入追加到标签中

<custominput></custominput>

Turns

<custominput>
   <input type='text'/>
</custominput>

and THEN I add any other validation attributes, like minlength and maxlength. 然后,我添加其他任何验证属性,例如minlength和maxlength。

In my plunkr, I can add attributes to the custominput tag, like that: 在我的plunkr中,我可以将属性添加到custominput标记中,如下所示:

<custominput compiled="compiled" disabled="disabled"></custominput>

But HOW can I add these attributes to the input tag (that means, the child of custominput)?? 但是如何将这些属性添加到输入标签(即custominput的子级)中?

UPDATE 1 更新1

This question can be summarized to: 这个问题可以概括为:

How can I add an HTML element/attributes with angular directives FROM a directive 如何从指令中添加带有角度指令的HTML元素/属性

EXAMPLE: Turn this 示例:转动

<form name="form0">
    <input custom-directive>
</form>

into this: 到这个:

<form name="form0">
    <input custom-directive type="text" ng-model="ctrl.username" ng-maxlength="15" ng-required="required">
</form>

from a directive 从指令

You would add them in the directive's template section. 您可以将它们添加到指令的模板部分。 See code below: 参见下面的代码:

html code HTML代码

<form>
    <input custom-directive>
</form>

directive code (im just writing this off the top of my head, it probably won't be a copy paste job for it to work, but it's definitely going in the right direction). 指令代码(我只是将其写在脑海中,它可能无法完成复制粘贴工作,但肯定会朝正确的方向发展)。

app.directive('customDirective', function() {
  return {
    restrict: 'A',
    controller: function($scope, attrService) {
      $scope.attributes = attrService.getAttrs;
    },
    link: function(scope, element, attrs) {
      element.attr('name', scope.attributes.name);
      // add more attributes
      console.log(scope.attributes) // ensure attributes is being pushed through from directive controller.
    }
  }
});

To dynamically add attributes 动态添加属性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM