How to link two Angular components through $routeProvider

Issue

I have some problem with Angular components:

Example:
myApp.js

angular.module('myApp', [])
.config(function($routeProvider) {
    $routeProvider
        .when('/login', {
            template: '<login></login>'
        })
        .when('/users', {
            template: '<users></users>'
        })
        .otherwise({redirectTo: '/login'});
});

In my project I have “main” component that contain ng-view.

main.js

angular.module('remoteGuiApp')
.component('main', {
    controller: function ($location, $window, $http) {
        //some code here
        //...
    },
    templateUrl: 'main.html'
});

main.html

<nav class="navbar navbar-default">
  <!-- ome navigation code-->
</nav>
<div ng-view>
</div>

Also I have “login” component
login.js

angular.module('remoteGuiApp')
.component('login', {
    controller: function () {
        //some code here
        //...
    },
    templateUrl: 'login.html'
});

So I need somehow connect events from “login” component to “main” component.
Technically “login” is nested of “main”, but it nested not directly but from $routeProvider. Maybe someone know how to do it? Thank’s for your help.

Solution

You can use $rootScope.$emit. Of course you have to inject it, and then like this, in child:

$rootScope.$emit('rootScope:authenticated', userData);

And in parent:

$rootScope.$on('rootScope:authenticated', function (event, userData) {
    alert(JSON.stringify(userData));
  })

Answered By – Radek Anuszewski

Answer Checked By – Robin (AngularFixing Admin)

Leave a Reply

Your email address will not be published.