【问题标题】:AngularJS: Writing Reusable Function for 'on-tag-added'AngularJS:为“添加标签”编写可重用函数
【发布时间】:2021-04-15 22:34:09
【问题描述】:

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

如果添加了禁止标签,则会

  1. 显示警告 [通过 {{warning1}} ]​​i>
  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 = '';
    }
  }

});

【问题讨论】:

    标签: angularjs ng-tags-input


    【解决方案1】:

    为你的函数添加额外的参数来设置标签的类型。

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

    【讨论】:

      猜你喜欢
      • 2013-09-01
      • 1970-01-01
      • 2017-05-08
      • 2021-05-15
      • 2021-09-29
      • 1970-01-01
      • 1970-01-01
      • 2011-02-13
      • 1970-01-01
      相关资源
      最近更新 更多