Search code examples
angularjsng-tags-input

AngularJS: Writing Reusable Function for 'on-tag-added'


There are many similar tags-input fields in the form that I will be creating. By using 'on-tag-added', I would like to check if any forbidden tags is added.

If a forbidden tag is added, it will

  1. Display a warning [through the {{warning1}} ]
  2. Remove the tag [through the pop() function]

I did mange to get it work but I have to define the function repeatedly (i.e onTagAdded1, onTagAdded2) with just different variable name inside.

How can I write this into a reusable code? Eg using service or directive?

Thank you.

HTML

<body ng-controller="MainCtrl">
  <tags-input ng-model="tags1" add-on-enter="true"
              on-tag-added="onTagAdded1($tag)">
  </tags-input>
  {{ warning1 }}
  <tags-input ng-model="tags2" add-on-enter="true"
              on-tag-added="onTagAdded2($tag)">
  </tags-input>
  {{ warning2 }}
</body>

JS

app.controller('MainCtrl', function($scope, $http) {

  $scope.onTagAdded1 = function($tag) {
    if ($tag.text == 'angular') {
      $scope.warning1 = $tag.text + ' is not allowed';
      $scope.tags1.pop();
    } else {
      $scope.warning1 = '';
    }
  }

  $scope.onTagAdded2 = function($tag) {
    if ($tag.text == 'angular') {
      $scope.warning2 = $tag.text + ' is not allowed';
      $scope.tags2.pop();
    } else {
      $scope.warning2 = '';
    }
  }

});

Solution

  • Add additional parameter to your function to set type of tag.

    HTML

      <body ng-controller="MainCtrl">
        <tags-input ng-model="tags1" add-on-enter="true" on-tag-added="onTagAdded($tag,1)"></tags-input>
      {{ warning1 }}
      <tags-input ng-model="tags2" add-on-enter="true" on-tag-added="onTagAdded($tag,2)"></tags-input>
      {{ warning2 }}
    </body>
    

    JS

    app.controller('MainCtrl', function($scope, $http) {
    
      $scope.onTagAdded = function($tag,type) {
        if ($tag.text == 'angular') {
          $scope['warning'+type] = $tag.text + ' is not allowed';
          $scope['tags'+type].pop();
        } else {
          $scope['warning'+type] = '';
        }
      }
    
    });