2016-06-02 6 views
0

Ich verwende Angular 1.5 Komponente in meiner Anwendung. Ich habe eine Stammkomponente für die Konfiguration meiner Routen:Wie erstelle ich ein Ereignis in Angular 1.5 Komponente

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" ] } 
    ] 
}); 

Ich habe auch eine Komponente login-partial innerhalb my-App Komponente zur Darstellung Login für Logout-Menü aufgerufen:

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

nun in meinem login-conponent ‚s Controller I wollen login-partial Vorlage ändern (die login Artikel zu logout ändern):

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] 
}); 

Mit Anweisungen könnten wir ein Ereignis unter Verwendung von $scope.$emit() and $scope.$on() auslösen. Aber soweit ich weiß, unterstützt die neue Komponente in Angular 1.5 keine Ereignisse.

Ist es mit Komponenten möglich? Irgendwelche Vorschläge, wie man dies erreichen könnte?

+1

Komponente ist [eine dünne Zuckerschicht] (https: //github.com/angular/angular.js/blob/v1.5.5/src/ng/compile.js#L1111) um die Direktive. Es kann dasselbe wie directive tun und verhindert nicht die Verwendung von $ scope im Controller. – estus

Antwort

0

I löste das Problem $rootScope und Versand ein Ereignis aus loginController Verwendung:

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); 
    }; 

}; 

Dann innen partialLoginController I zu diesem Fall hört:

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

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