【发布时间】:2021-04-15 22:34:09
【问题描述】:
我将创建的表单中有许多类似的标签输入字段。 通过使用'on-tag-added',我想检查是否添加了任何禁止的标签。
如果添加了禁止标签,则会
- 显示警告 [通过 {{warning1}} ]i>
- 删除标签[通过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 = '';
}
}
});
【问题讨论】: