The key to solving this problem is that you must use the $ compilation service in the HTML returned by the formatNoMatches function in the options object. At this stage of compilation, the ng-click directive will be created in the markup for the area. Unfortunately, this is a little easier said than done.
Here you can see the full working example: http://jsfiddle.net/jLD42/4/
I do not know how AngularJS can monitor the select2 control to control the search results, so we must tell the controller when the results are not found. This is easily done using the formatNoMatches function:
$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; } };
The $scope.noResultsTag property $scope.noResultsTag track of the last value entered by the user that did not return matches. Wrapping upgrades to $scope.noResultsTag using $ scope. $ Apply is necessary because formatNoMatches is called outside the context of the digest AnglerJS loop.
We can observe $scope.noResultsTag and compile formatNoMatches markup when changes occur:
$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);
You may wonder what the timeout of $ does there. It is used to avoid race conditions between the select2 control updating the DOM with formatNoMatches markup and the watch function trying to compile this markup. Otherwise, there is a good chance that the $('.select2-no-results') selector will not find what it is looking for and will not compile at compile time.
After the link to the add tag has been compiled, the ng-click directive will be able to call the addTag function on the controller. You can see this in action in jsFiddle. By clicking the "Add tag" link, you will update the tag array with the search term that you enter in the select2 control, and you can see it in the markup and the list of options the next time you enter a new search term in the select2 control.
Justin lovero
source share