我在我的应用程序中使用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中引入的新组件不支持事件。
组件可以吗?关于如何实现这一目标的任何建议?
答案 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);
});
};