AngularJS Select2 No Results

by aljordan82

HTML

<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/select2/3.4.0/select2.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/select2/3.4.0/select2.min.js"></script>
<script src="https://rawgithub.com/angular-ui/ui-select2/master/src/select2.js"></script>

<div ng-controller="MyCtrl">
    No Results Tag: {{ noResultsTag }}
    <br />
    <select style="width: 400px;" ui-select2="select2Options" multiple ng-model="selectedTags">
        <option ng-repeat="tag in tags" value="{{tag.id}}">{{tag.name}}</option>
    </select>
    <br /><br />
    Tags: 
    <pre>
        {{ tags | json }}
    </pre>
</div>

CSS

a:hover {
    text-decoration: underline;
    color: blue;
    cursor: pointer;
}

JavaScript

var myApp = angular.module('myApp', ['ui.select2']);

function MyCtrl($scope, $compile, $timeout) {
    $scope.noResultsTag = null;
    $scope.tags = [
        {id: 0, name: "Zero"},
        {id: 1, name: "One"},
        {id: 2, name: "Two"}, 
        {id: 3, name: "Three"}, 
        {id: 4, name: "Four"}, 
    ];
    $scope.select2Options = {
        formatNoMatches: function(term) {
            console.log("Term: " + term);
            var message = '<a ng-click="addTag()">Add tag:"' + term + '"</a>';
            if(!$scope.$$phase) {
                $scope.$apply(function() {
                    $scope.noResultsTag = term;
                });
            }
            return message;
        }
    };
    
    $scope.addTag = function() {
        $scope.tags.push({
            id: $scope.tags.length,
            name: $scope.noResultsTag
        });
    };
    
    $scope.$watch('noResultsTag', function(newVal, oldVal) {
        if(newVal && newVal !== oldVal) {
            $timeout(function() {
                var noResultsLink = $('.select2-no-results');
                console.log(noResultsLink.contents());
                $compile(noResultsLink.contents())($scope);
            });
        }
    }, true);
}