HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

AngularJS Tab Control

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
tabangularjscontrol

Problem

I'm experimenting with angular directives, and as a proof of concept I wanted to create a basic tab control. I'd like to know if anything can be changed to be more fluid, or if I'm doing things "right".

Live Example: http://jsfiddle.net/6wa2x/

HTML (with embedded angular templates):


        
            Tab 1 stuff
        
        
            Tab 2 stuff
        
        
            Tab 3
        
    

    
        
            
                {{tab.name}}
            
        
    

    
        
            {{tab.name}}
        

        
        
    

    
        
            
                {{ name }}
            
            
            
        
    
    


Javascript:

```
var mainModule = angular.module("mainModule", []);

mainModule.directive('tabControl', function() {
return {
restrict: 'E',
templateUrl: 'tabControlTemplate',
scope: {
id: '@id',
klass: '@class',
},
transclude: true,
controller: ['$scope', function($scope) {
$scope.tabs = []

this.addTab = function(tab){
$scope.tabs.push(tab);
}

$scope.selectTab = function(tab){
for(var i=0; i<$scope.tabs.length; i++){
if(tab.name != $scope.tabs[i].name){
$scope.tabs[i].selected = false;
}
else {
$scope.tabs[i].selected = true;
}
}
}
}]
};
});

mainModule.directive('tab', function(){
return {
restrict: 'E',
templateUrl: 'tabTemplate',
transclude: true,
replace: true,

Solution

From a once over:

-
It seems both ` and will share the id Tab1, that's not good

-
I am not sure what the point is of setting
name in the elements, id should suffice

-
I am not sure what the point is of
tab2ContentTemplate, deleting it does not change functionality

-
This :

if (tab.name != $scope.tabs[i].name) {
    $scope.tabs[i].selected = false;
} else {
    $scope.tabs[i].selected = true;
}


could be

$scope.tabs[i].selected = ( tab.name == $scope.tabs[i].name );


-
There are some minor style issues you could find/solve by using jshint.com

All in all, I find the HTML part very hard to follow, only after playing with it for a while did I really grasp what you are doing. You should carefully review the
id's you employ. For example: tabTemplate <- I would call this articleTemplate` perhaps ?

Code Snippets

if (tab.name != $scope.tabs[i].name) {
    $scope.tabs[i].selected = false;
} else {
    $scope.tabs[i].selected = true;
}
$scope.tabs[i].selected = ( tab.name == $scope.tabs[i].name );

Context

StackExchange Code Review Q#46927, answer score: 4

Revisions (0)

No revisions yet.