我有以下HTML
<html ng-app="app" ng-csp="">
<body ng-controller="MainController" capture ng-class="view">
<div id="wrap" ng-switch="view">
<div id="login" ng-switch-when="login" ng-controller="SignInController">
my login code
</div>
<div id="project" ng-switch-when="project" ng-controller="ProjectController">
my login code
</div>
</div>
</body>
</html>
我的Angular代码是
var app = angular.module("app", []);
app.controller("MainController", ["$scope", function(t) {
/* check session if exist or not if not show login*/
t.view='login';
}]),app.controller("SignInController", ["$scope","$http", function(t,$http) {
t.signIn = function() {
$http({
url: "/login/",
data: { email: t.user.email,password:t.user.password },
method: 'POST',
}).success(function (data) {
console.log(data);
//want to show project div
t.$emit("view", "project");
}).error(function(err){
t.error = "Invalid Login";
})
};
}]),app.controller("ProjectController", ["$scope", function(t) {
}]);
现在我的ng-swicth并没有成功。 编辑: 这里是punker链接http://plnkr.co/edit/I8EEFM8gdplUmNaZoYc6
当我点击登录按钮时,我想显示项目切换。
任何建议
由于
答案 0 :(得分:3)
问题是您的控制器之间不共享$ scope。首先只有一个Controller,因此$ scope是按照您的期望共享的。
将ExampleController更改为:
var app = angular.module("switchExample", []);
app.controller("ExampleController", ["$scope", function($scope) {
$scope.selection ="settings";
$scope.signIn = function() {
alert("click");
$scope.selection ="project";
}
}]);
...当您单击“登录”时,删除其他控制器和HTML中未使用的控制器的引用将显示“hello”
答案 1 :(得分:2)
我认为你弄错了。 ng-switch的语法是:
<ANY ng-switch="expression">
<ANY ng-switch-when="matchValue1">...</ANY>
<ANY ng-switch-when="matchValue2">...</ANY>
<ANY ng-switch-default>...</ANY>
</ANY>
它使用变量($ scope的成员)并且与事件无关。
而不是t.$emit("view", "project");
你应该$scope.view = "project";
。
请参阅文档底部的示例:https://docs.angularjs.org/api/ng/directive/ngSwitch
答案 2 :(得分:0)
你试过了吗?
<div id="wrap" ng-switch on="view">
并设置:
$scope.view = "project";
答案 3 :(得分:0)
<html ng-app="app" ng-csp="">
<body ng-controller="MainController" capture ng-class="view">
<div id="wrap" ng-switch on="view">
<div id="login" ng-switch-when="'login'" ng-controller="SignInController">
my login code
</div>
<div id="project" ng-switch-when="'project'" ng-controller="ProjectController">
my login code
</div>
</div>
</body>
使用此html