0

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.

jemiloii
  • 24,594
  • 7
  • 54
  • 83
Sergaros
  • 821
  • 1
  • 5
  • 14
  • 1
    Possible duplicate of [Share data between AngularJS controllers](http://stackoverflow.com/questions/21919962/share-data-between-angularjs-controllers) – Deblaton Jean-Philippe Apr 28 '17 at 13:35
  • Controller and Component is very different Essence, besides I know how connect them but not through $routeProvider. Please read my question) – Sergaros Apr 28 '17 at 13:39
  • I've read your question. Each component contains a controller. The route provider has no effect on your issue, you can just forget about it for this case. – Deblaton Jean-Philippe Apr 28 '17 at 13:41
  • Otherwise, you can also use $rootScope.emit(); – Deblaton Jean-Philippe Apr 28 '17 at 13:43
  • In componets scope is always isolate. – Sergaros Apr 28 '17 at 13:52
  • When the router switches views, it destroys the old component and its controller and removes it from the DOM. It then builds the new component and its controller and adds it to the DOM. Any data that needs to persist between different views needs to be stored elsewhere. Use a service to do that. See [AngularJS Developer Guide - Creating Services](https://docs.angularjs.org/guide/services#creating-services). – georgeawg Apr 28 '17 at 17:26

1 Answers1

1

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));
  })
Radek Anuszewski
  • 1,812
  • 8
  • 34
  • 62