我将要创建的表单中有许多类似的标记输入字段。通过使用"on tag added",我想检查是否添加了任何禁止的标签。
如果添加了禁止的标签,它将
- 显示警告[通过{{warning1}}]
- 删除标记[通过pop((函数]
我确实设法让它工作了,但我必须重复定义函数(即onTagAdded1、onTagAdded 2(,其中只有不同的变量名。
如何将其写入可重用代码?例如使用服务或指令?
谢谢。
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] = '';
}
}
});