Sirwan Afifi Sirwan Afifi - 3 months ago 8
Javascript Question

How to raise an event in Angular 1.5 Component

I'm using Angular 1.5 Component in my application. I have a root component for configuration my routes:

module.component("myApp", {
templateUrl: "/app/components/my-app.component.html",
$routeConfig: [
{ path: "/list", component: "myList", name: "List" },
{ path: "/login", component: "login", name: "Login" },
{ path: "/**", redirectTo: [ "List" ] }
]
});


I also have a component called
login-partial
inside
my-App
component for showing login for logout menu:

<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li>
<a href="#/login">Login</a>
</li>
</ul>
</div><!--/.nav-collapse -->


Now, inside my
login-conponent
's controller I want to change
login-partial
template (changing the
login
item to
logout
):

function loginController(account, $location) {
var model = this;
var onComplete = function (data) {
if (data === "ok") {
$location.url('/list');
}
};
model.login = function (userName, password) {
account.login(userName, password)
.then(onComplete, onError);
};
};
module.component("login", {
templateUrl: "/app/components/login.component.html",
controllerAs: "model",
controller: ["account", "toaster", "$location", loginController]
});


With directives we could raise an event using
$scope.$emit() and $scope.$on()
. But as far as I know the new component introduced in Angular 1.5 doesn't support events.

Is it possible with components? Any suggestion as to how one would achieve doing this?

Answer

I solved the problem using $rootScope and dispatch an event from loginController:

function loginController(account, toaster, $location, $rootScope) {
    var model = this;

    var onComplete = function (data) {
        if (data === "ok") {
            $rootScope.$emit('success', { data: true });
            $location.url('/list');
        }
        // other code
    };
    var onError = function (reason) {
        // other code
    };

    model.login = function (userName, password) {
        account.login(userName, password)
            .then(onComplete, onError);
    };

};

Then inside partialLoginController I listen to that event:

function partialLoginController($rootScope) {
    var model = this;
    model.isLoggedIn = false;

    $rootScope.$on('success', function (event, args) {
        model.isLoggedIn = args.data;
        console.log(args.data);
    }); 
};
Comments