AngularJS:为 'on-tag-added' 编写可重用函数

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

我将创建的表单中有许多类似的标签输入字段。 通过使用'on-tag-added',我想检查是否添加了任何禁止的标签。

如果添加禁止标签,它将

  1. 显示警告[通过{{warning1}}]
  2. 删除标签[通过 pop() 函数]

我确实设法让它工作,但我必须重复定义函数(即 onTagAdded1、onTagAdded2),只是内部变量名称不同。

如何将其写入可重用代码?例如使用服务或指令?

谢谢。

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 = '';
    }
  }

});

向您的函数添加附加参数以设置代码类型。

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] = '';
    }
  }

});