Search code examples
angularjsng-tags-input

ngtagsinput angularjs How to assign id to each tag


I'm using ngtagsinput (http://mbenford.github.io/ngTagsInput/) to add highlight functionality to my app. I can't figure out how dynamically add an id for each tag as its being created. I will be using this id to edit the styling of each tag item after it has been created. I saw the demo about custom templates, but this only works if you pre-define the array of tags. I'm a newb to Angular which is probably the issue... Any hints?


Solution

  • You can add the id using an on-tag-added handler. I made a very simple logic that appends the number of tags as id, but you can do whatever you want.

    $scope.onTagAdded = function($tag) {
        var index = $scope.tags.indexOf($tag);
        $scope.tags[index].id = $scope.tags.length;
    };
    

    And in the HTML:

    <tags-input ng-model="tags" on-tag-added="onTagAdded($tag)"></tags-input>
    

    You can then use the appended id in your custom template if needed. See this Plunker.