Rishabh Rishabh - 3 months ago 18
AngularJS Question

How to enable lazy loading on tabs in tabset in Angular js?

I making

<tabset>
view to show the content in a page. Also I am using
Bootstrap's Tabs and Lazy Data Loading so that the controller for a particular tab is initialized only when it is active. I am able to achieve lazy loading for the tabs.

<div id="panel" ng-controller="HomeController as hmctrl">
<tabset>
<tab class="nav-item" id="tab_content" title="Tab1" template-url="app/components/tab1/tab1.html"></tab>
<tab class="nav-item" id="tab_content" title="Tab2" template-url="app/components/tab2/tab2.html"></tab>
<tab class="nav-item" id="tab_content" title="Tab3" template-url="app/components/tab3/tab3.html"></tab>
</tabset>
</div>


In my app.config I have only one route for the main page

var app = angular.module('myApp', ['bootstrap.tabset','ngRoute']);

app.config(
function($routeProvider,$locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'app/components/home/homeView.html'
});
});


For every tab there is a separate controller assigned to them.
I would like to know how to assign routes to any particular tabs when created this way. So that I can navigate to them using
$location.path()
function.

I have created a plnkr for the same here
Plnkr for the above described scenario

Answer

You should be using $stateProvider instead of $routeProvider in this case. I have forked your plunker here- https://plnkr.co/edit/lL9JVRmuE8kQ5f0WhRDo?p=preview

var app = angular.module('myApp', ['bootstrap.tabset','ngRoute','ui.router']);

app.config(
  function($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise("/Home");

    $stateProvider
    .state('Home', {
      url: "/Home",
      templateUrl: "home.html"
    })
    .state('Home.Tab1', {
      url: "/Tab1",
      templateUrl: "tab1.html"
    })
    .state('Home.Tab2', {
      url: "/Tab2",
      templateUrl: "tab2.html"
    })
    .state('Home.Tab3', {
      url: "/Tab3",
      templateUrl: "tab3.html"
    });

});

Index.html - use ui-view instead of ng-view

<div class="ui-view"></div>

Home.html

<div id="panel" ng-controller="HomeController as hmctrl">
  <p>Home</p>
<tabset>
<tab  class="nav-item" id="tab_content" title="Tab1" ui-sref=".Tab1"></tab>
<tab  class="nav-item" id="tab_content" title="Tab2" ui-sref=".Tab2"></tab>
<tab  class="nav-item" id="tab_content" title="Tab3" ui-sref=".Tab3"></tab>
</tabset>

<div ui-view></div>
</div>

The url will be #/Home/Tab1 ,#/Home/Tab2, #/Home/Tab3 and you could force navigate to the state by:

 $state.go("Home.Tab2");//navigates to Tab2 of Home page

More about state providers here - https://github.com/angular-ui/ui-router

Make sure you refer state provider script and inject this module in your app