nish
nish

Reputation: 256

How to implement url for dynamic tabs in Angularjs

I have displayed dynamic tab menu's using ng-repeat and i want to get individual url for each tab is it possible to get the url? if so how can i handle the route. i think its not possible to to set the route because of the dynamic tab content, is there any other options available?

Upvotes: 3

Views: 1139

Answers (1)

Ilan Frumer
Ilan Frumer

Reputation: 32397

It's just a little patch, In a real application I recommend using ng-route OR ui-router.

Add url property to tabs

$scope.tabs = [
  { url: "/tab/1" , title:"Tab 1", content:"Dynamic content 1" },
  { url: "/tab/2" , title:"Tba 2", content:"Dynamic content 2" },
  { url: "/tab/3" , title:"Tab 3", content:"Dynamic content 3" },
  { url: "/tab/4" , title:"Tab 4", content:"Dynamic content 4" }
];

I Created A directive that:

  • changes the location based on active tab ( on $watch )
  • changes the active tab based on the location ( on prelink phase )
app.directive('tabRoute',function($location,$timeout){
  return {
    scope: {
      tabRoute : "="
    },
    compile: function(){
      return {
        pre: function(scope,elm,attrs){
          scope.tabRoute.active = ($location.path() === scope.tabRoute.url);
        },
        post: function(scope,elm,attrs){
          scope.$watch('tabRoute.active',function(){
            if(scope.tabRoute.active) {
              $location.path(scope.tabRoute.url)
            }
          })          
        }
      }     
    }
  }
})

finally, the markup

<tab ng-repeat="tab in tabs" 
     heading="{{tab.title}}" 
     active="tab.active" 
     disabled="tab.disabled" 
     tab-route="tab">

Upvotes: 3

Related Questions