Looking for good programming challenges?

Use the search below to find our solutions for selected questions!

Simple token field for AngularJS

Sharing is caring!

I was searching the net for a very, very simple token field for AngularJS the other day to use on a side project that I was working on. Unfortunately I couldn’t find anything that suits my requirements. So I implemented my own. Here is how to use it.

(Optional) Install Using bower
Add ng-token-field as a dependency to your project within your bower.json file

  "dependencies": {
    "ng-token-field": "lucaslouca/ng-token-field"

Then do a bower install in your project directory:

$ bower install

Import JQuery
The directive requires JQuery.

Import the ng-token-field stylesheet and script
Include the stylesheet and javascript files:


Add the dependency to your module
Add the ngTokenField module as a dependency in your AngularJS app;

angular.module('MyApp', ['ngTokenField'])...

Add the <ng-token-field> element to your DOM
Add the custom element to the HTML file where you want to use and bind it to a property and/or validator function.


(Optional) Add a token text validator
You can also define a validator function that validates the text of each token and styles it accordingly. Below we define a function validator that returns true if the text is an email and false otherwise.

.controller('MyController', function($scope) {
    $scope.validator = function(text) {
        // Check if token text is an email
        var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(text);
    $scope.tags = [];

A non AngularJS version is also available here, which does not require JQuery.

Full code & Demo