Search code examples
javascriptangularjsangular-ui-routerangularjs-components

How to use ui-sref in ui-router AngularJS


i have file index.html:

<!DOCTYPE html>
<html>
<head>
    <style>
        .navbar { border-radius:0; }
    </style>
    <link rel="stylesheet" type="text/css" href="lib/css/bootstrap.min.css">
    <script src="./node_modules/angular/angular.js"></script>
    <script src="./node_modules/angular-ui-bootstrap/dist/ui-bootstrap-tpls.js"></script>
    <script src="./node_modules/angular-ui-router/release/angular-ui-router.js"></script>
    <script src="lib/js/app.js"></script>
</head>

<body ng-app="nav-module">
    <a ui-view="home" ui-sref="home" ui-sref-active="active">home</a>
    <a ui-view="about" ui-sref="about" ui-sref-active="active">about</a>
        <ui-view>
        </ui-view>

</body>
</html>

and file app.js:

var app = angular.module("nav-module", ["ui.router",'ui.bootstrap']);
app.component('navComponent',{
    templateUrl: './navbar.component.html'
});
app.config(['$stateProvider',
'$urlRouterProvider',function($stateProvider,$urlRouterProvider) {
    $stateProvider
    .state('/home',{
        name: 'home page',
        url:'/home',
        template: '<h3>hello world!</h3>'
    })
    .state('/about',{
        url:'/about',
        component: 'navComponent'
    });
    $urlRouterProvider.otherwise('/home');
}]);

and nav-bar.component.html:

<h1>nav bar</h1>

but i can't click to tag to run page, and when i change /about in URL, the console show error:

Failed to load template: ./navbar.component.html

i dont know why.


Solution

  • I think you're missing the templateurl location or file name as you mention that your templateUrl:'./navbar.component.html' but your file name is nav-bar.component.html.

    1. First remove templateUrl & check it by using template: <h1>nav bar</h1> in component.
    2. If it's OK,then your error is for just missing the templateUrl refrence or the file name.
    3. Then fix this by using ../app/navtemplateurl.html and file name is navtemplateurl.html which is inside the app folder.

    Adding 'ui.bootstrap.tpls' in your module can also solve this problem

    Update: ust change the angularui router refrence from index file to <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.0-rc.1/angular-ui-router.js"></script> as component templates in ui-router are not supported in v0.4.2 or earlier. You also need to update this.

    enter image description here