Backus
Backus

Reputation: 43

How can I add or remove a tag with ng-tags-input within a function

I am using ng-tags-input, and trying to modify the input so that only tags which are permitted can be added. For example, an array contains 'Tag1' but not 'T1', and so when 'T1' is entered in the input bar it is not accepted, but 'Tag1' is because it is 'permitted'.

Thanks.

Upvotes: 1

Views: 6314

Answers (2)

writeToBhuwan
writeToBhuwan

Reputation: 3281

Just in case are trying to put a check for Email ID, below is the code. In case of other validation, please change the validation function accordingly.

HTML:

<tags-input ng-model="tagList" add-on-space="true" add-on-comma="true" add-on-blur="true" add-on-enter="true" on-tag-added="tagAdded($tag);" placeholder="Add comma separated email id's" ></tags-input>

Controller:

$scope.tagList = ['[email protected]', '[email protected]'];
$scope.tagAdded=function(tag){    
    var textEntered=tag.text;       
    var isVaildEmail=validateEmail(tag.text);
    console.log($scope.tagList);
    if(isVaildEmail){
       console.log(true); //do something
    }
    else{
       $scope.tagList.splice($scope.tagList.indexOf(tag),1); //remove the aded tag from ng-model of the input. i.e. tagList
    } 
}
function validateEmail(email) {
    var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    return re.test(email);
}

Upvotes: 1

Michael Benford
Michael Benford

Reputation: 14114

Currently there's no built-in way to perform such validation. But I think you can use a different approach:

  • Use the autoComplete directive to provide the user with the list of valid country codes;
  • Set the addFromAutocompleteOnly option to true, so only tags coming from the autocomplete list will be allowed.

HTML

<tags-input ng-model="countryCodes" add-from-autocomplete-only="true">
   <auto-complete source="loadCountryCodes($query)"></auto-complete>
</tags-input>

Working Plunk

Upvotes: 4

Related Questions