To effectively tackle this issue, it is crucial to utilize the $compile service on the HTML outputted by the formatNoMatches
function within the options object. This process of compilation connects the ng-click directive in the markup to the scope. However, achieving this task is not as simple as it may seem.
For a comprehensive demonstration, visit this link: http://jsfiddle.net/jLD42/4/
In AngularJS, there isn't a direct method to monitor the select2 control for search results. Therefore, we must notify the controller when no matches are found, which can be accomplished through 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
variable stores the most recent value entered by the user that did not yield any matches. Wrapping the update to $scope.noResultsTag
with $scope.$apply is essential because formatNoMatches
is invoked outside the AngularJS digest loop.
We can observe changes in $scope.noResultsTag
and compile the formatNoMatches
markup accordingly:
$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 might question the use of $timeout in this context. It serves to prevent a race condition between the select2 control updating the DOM with the formatNoMatches
markup and the watch function attempting to compile said markup. Without this precaution, there is a risk that the $('.select2-no-results')
selector will not find the desired elements, potentially rendering the compilation ineffective.
Once the add tag link has been compiled, the ng-click
directive enables the invocation of the addTag
function within the controller. This functionality can be witnessed firsthand on the jsFiddle provided. By clicking the add tag link, you can update the Tags array with the search term inputted into the select2 control, with the new addition appearing in both the markup and the options list upon entering a subsequent search term.