tags.js

angular.module('homepage').
directive('tags', function() {
    return {
        restrict: 'E',
        replace: true,
        scope: {
            tags: '='
        },
        link: tagLinker,
        templateUrl: 'components/common-components/tags/tags.html'
    };
}).
directive('tagsAutocomplete', function() {
    return {
        restrict: 'E',
        replace: true,
        scope: {
            choices: '=',
            /**
            * Entered text not converted to tag
            * @type {String}
            */
            enteredtext: '=',
            minlength: '=',
            result: '=',
            type: '=',
            /**
            * Tags list
            * @type {Array}
            */
            tags: '='
        },
        link: tagLinker,
        templateUrl: 'components/common-components/tags/tags-autocomplete.html'
    };
});

function tagLinker(scope, element, attribute) {
    scope.placeholder = attribute.placeholder;

    scope.addTag = function() {
        if (scope.enteredtext !== undefined && scope.enteredtext.length === 0) {
            return;
        }

        scope.tags.push({'text': scope.enteredtext});
        scope.enteredtext = '';
        return scope.enteredtext;
    };

    scope.deleteTag = function(index) {
        if (scope.tags.length > 0 && scope.enteredtext.length === 0 && index === undefined) {
            scope.tags.pop();
        } else {
            if (index !== undefined) {
                // Remove item at index 'index'
                scope.tags.splice(index, 1);
            }
        }
        return scope.tags;
    };

    element.bind('keydown', function(event) {
        var key = event.which;
        if ((!event.shiftKey && key === 9) || key === 13 || key === 188) {
            if(!(scope.enteredtext !== undefined && scope.enteredtext.length === 0)) {
                event.preventDefault();
                scope.$apply('addTag()');
            }
        }
        else if (key === 8) {
            scope.$apply('deleteTag()');
        }
    });
}