簡體   English   中英

帶有父子控制器的Angular中的ng-switch

[英]ng-switch in Angular with Parent Child Controller

我有以下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不會為成功而煩惱。 編輯:這是朋克鏈接http://plnkr.co/edit/I8EEFM8gdplUmNaZoYc6

當我單擊登錄按鈕時,我想顯示項目開關。

有什么建議么

謝謝

問題是$ 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中對未使用的控制器的引用將顯示“你好”

我想你錯了。 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

你有沒有嘗試過:

<div id="wrap" ng-switch on="view">

並設置:

$scope.view = "project";
<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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM