Personally, I believe that implementing a custom directive can greatly enhance the cleanliness of your code, especially when working with AngularJS.
Here is a comprehensive solution utilizing an AngularJS Custom Directive that promotes code reusability and organization.
HTML
Custom Directive Default Behavior
<ul data-my-directive class="list">
<li>a</li>
<li>b</li>
<li>c</li>
</ul>
(The following is a preview screenshot. Refer to the PLAYGROUND link below for interactive exploration)
HTML
With Custom Attribute
<ul data-my-directive data-multi-select="true" class="list">
<li>a</li>
<li>b</li>
<li>c</li>
</ul>
(The following is a preview screenshot. Refer to the PLAYGROUND link below for interactive exploration)
Javascript
angular.module('app',[])
.directive('myDirective', function(){
return {
transclude: true,
template: '<div ng-transclude></div>',
link: function(scope, element, attrs){
function addClickListener(i, callback){
selections[i].addEventListener('click', function(){
callback(i);
}, false);
}
// Set up attribute value. Goes to default if attribute is not set up
attrs.multiSelect = attrs.multiSelect || 'false';
scope.isSelected = [];
var selections = element[0].getElementsByTagName('li');
if(attrs.multiSelect === "true"){
for(var i = 0; i < selections.length; i++){
scope.isSelected[i] = false;
addClickListener(i, function(i){
if(scope.isSelected[i] === true){
// if previously it is selected (red color), now make it unselected (black color / default color)
angular.element(selections[i]).removeClass('selected');
scope.isSelected[i] = false;
} else {
// previously black color, so change it to red color
angular.element(selections[i]).addClass('selected');
scope.isSelected[i] = true;
}
});
}
} else {
var currentSelection = -1;
for(var i = 0; i < selections.length; i++){
scope.isSelected[i] = false;
addClickListener(i, function(i){
if(scope.isSelected[i] === true){
// do nothing
} else {
// previously black color, so change it to red color
angular.element(selections[i]).addClass('selected');
scope.isSelected[i] = true;
angular.element(selections[currentSelection]).removeClass('selected');
scope.isSelected[currentSelection] = false;
currentSelection = i;
}
});
}
}
}
}
});
And lastly, the ultimate
PLAYGROUND
for hands-on experimentation! Enjoy exploring :) Have a wonderful day!