如何在Angular 1.5 Component中引发事件

时间:2016-06-02 12:51:44

标签: javascript angularjs

我在我的应用程序中使用Angular 1.5 Component。我有一个用于配置路由的根组件:

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

我还在login-partial组件中有一个名为my-App的组件,用于显示注销菜单的登录信息:

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

现在,在我的login-conponent控制器中,我想更改login-partial模板(将login项更改为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]
});

使用指令,我们可以使用$scope.$emit() and $scope.$on()引发事件。但据我所知,Angular 1.5中引入的新组件不支持事件。

组件可以吗?关于如何实现这一目标的任何建议?

1 个答案:

答案 0 :(得分:0)

我使用$rootScope解决了问题,并从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);
    };

};

然后在partialLoginController内我听那个事件:

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

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