多标签输入字段

时间:2016-07-12 11:21:21

标签: javascript html angularjs forms

我最近开始使用AngularJS,目前正在处理一个带有标签输入字段和提交按钮的简单表单。输入字段应该接受多个标记,以便在单击提交时所有标记都保存为数组。

现在我正在使用我在github(http://mbenford.github.io/ngTagsInput/)上找到的ngTagsInput指令。该指令为我提供了<tags-input></tags-input> HTML元素,该元素创建了一个输入字段,在提交之前接受多个标记。这是它的样子(查看标签字段):

enter image description here

这很好用,我现在需要的是一个指令,它给了我类似的功能,但不是一个元素即。 <tags-input>,我想要一个属性,我可以将其包含在<input>这样的传统<input attribute='tags-input'>元素中。

问题:

  1. 有没有办法可以使用ngTagsInput作为属性?
  2. 是否有其他指令可能符合我的需要?如果是,那么请在答案中发布链接。
  3. 提前致谢。

1 个答案:

答案 0 :(得分:1)

没有。正如您在tags-input.js文件中看到的那样,该指令配置为element

return {
    restrict: 'E',
    require: 'ngModel',
    scope: {
        tags: '=ngModel',
        text: '=?',
        templateScope: '=?',
        tagClass: '&',
        onTagAdding: '&',
        onTagAdded: '&',
        onInvalidTag: '&',
        onTagRemoving: '&',
        onTagRemoved: '&',
        onTagClicked: '&',
    },

但您可以使用attribute类型编写自己的指令,并将div element“替换”为tags-input element

我写了这个例子:

app.directive('tagsInputAttr', 
  function($compile){
    return {
      restrict: 'A',
      require: '?ngModel',
      scope:{
        ngModel: '='
      },
      link: function($scope, element, attrs, controller) {
        var attrsText = '';
        $.each($(element)[0].attributes, function(idx, attr) {
          if (attr.nodeName === "tags-input-attr" || attr.nodeName === "ng-model") 
            return;

          attrsText += " " + attr.nodeName + "='" + attr.nodeValue + "'";
        });

        var html ='<tags-input ng-model="ngModel" ' + attrsText + '></tags-input>';
        e =$compile(html)($scope);
        $(element).replaceWith(e);
      }
    };
  }
);

现在,您可以通过两种方式配置标签输入元素:

元素方式:

<tags-input ng-model="tags" add-on-paste="true" display-property="text" placeholder="Add a Tag here..." ></tags-input>

属性方式:

<input tags-input-attr ng-model="tags" add-on-paste="true" display-property="text" placeholder="Add a Tag here..."  />

你可以在Plunker看到这个:

https://plnkr.co/edit/yjkX22

相关问题