【问题标题】:Ng-switch not workingNg开关不工作
【发布时间】:2016-03-11 11:58:06
【问题描述】:

我正在使用 ng-switch,如下所示。这是ng-switch的正确用法吗?我不希望它在数组中,因为我将它与范围变量一起使用。

在我的 HTML 中,我已将其定义如下。 userRole 是我希望我的搜索所基于的变量,在 when 中我使用了基于我的 div 标签内容应该使用的值。

<div ng-switch on ="userRole">
  <div ng-switch-when="admin">
     [...]
  </div>
  <div ng-switch-when="user">
     [...]
  </div>

我无法访问 ng-switch 的功能,我的整个内容部分都消失了。

在我的 .js 文件中,我定义了以下内容:

if(loginModel.authorities[0].authority=="ROLE_ADMIN"){
  console.log("Me here");
  $scope.userRole="admin";
}
else
if(loginModel.authorities[0].authority=="ROLE_USER"){
  $scope.userRole="user";

}
else{
  $scope.userRole="guest";
}

但是我的屏幕没有显示任何东西,这让我想知道我应该如何使用 ng-switch。我不想使用 ng-hide / ng-show。

【问题讨论】:

  • console.log() 中显示变量$scope.userRole。因为ng-switch 按预期工作。 jsfiddle 上的示例。

标签: angularjs ng-switch


【解决方案1】:

这是我在 ng-switch 的工作原理上发现的一个简洁的小提琴......你使用 ng-switch 的方式是完全有效的。我猜你的userRole 没有任何价值,这使它失败,你能仔细检查一下吗?

<div ng-controller="LoginCheckCtrl">
   <div ng-switch on="loginData"> 
      <div ng-switch-when="false" ng-include="'login'"></div>
      <div ng-switch-when="true" ng-include="'logout'"></div>
   </div>
</div>

<script type="text/ng-template" id="login">
    <button ng-click="login()">Login</button>
</script>

<script type="text/ng-template" id="logout">
    <button ng-click="logout()">Logout</button>
</script>

控制器代码:

var app = angular.module('myApp', []);

function LoginCheckCtrl($scope) {
    $scope.loginData = false
    $scope.login = function() {
        console.log($scope.loginData  ? 'logged in' : 'not logged in');
        $scope.loginData = true;
    };
    $scope.logout = function() {
        console.log($scope.loginData ? 'logged in' : 'not logged in');
        $scope.loginData = false;
    };
}

小提琴 https://jsfiddle.net/mrajcok/jNxyE/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-25
    • 2017-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-15
    • 2017-09-27
    相关资源
    最近更新 更多