Component based routing using ui-router | AngularJS

64 Views Asked by At

We had created a component named contact using [email protected] and [email protected] problem lies on click of a button,nothing is displayed in the home page.It would be great if someone could help us to figure out the error.

index.html

<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
    <meta charset="utf-8">
    <title>Component based routing</title>
    <!--Styles-->

    <!--Libs-->
    <script src="../libs/angular.js"></script>
    <script src="../libs/angular-ui-router.js"></script>

    <!--Components-->
    <script src="app.js"></script>
    <script src="contact/contact.js"></script>
    <script src="contact/contact.component.js"></script>

</head>

<body>
    <h1>Component based routing</h1>
    <div ng-app="app">
        <ul>
            <li>
                <a href="#/contact">Contact</a>
            </li>
        </ul>
        <h4>Test</h4>
        <ui-view></ui-view>
    </div>
</body>

</html>

app.js

angular.module('app',[]);

contact.js

angular
    .module('contactApp', ['ui-router']);

contact.component.js

angular
    .module('contactApp')
    .config(['$stateProvider',function ($stateProvider) {
        $stateProvider.state('contact', {
                url: '/contact',
                component: 'contact'
            })
    }])
    .component('contact',{
        template: `<h1>Contact</h1>`
    })
1

There are 1 best solutions below

1
Bill P On

You app module, where component is registered, is contactApp. You need to change html to that app module:

<div ng-app="contactApp">

EDIT

If we assume that app is the main app module and there are other modules declared, then all the other have to be registered under that main app like this:

angular.module('app', ['contactApp']);

and then in html you use app, as you already do:

<div ng-app="app">

*You can also have multiple apps in the same html but it is not the recommented way