繁体   English   中英

Angular JS:ng-hide和ng-show API

[英]Angular JS: ng-hide and ng-show API

我有一个包含几个<div>容器的HTML页面。 我需要根据用户ID显示这些<div>容器。 例如:我在页面中创建了4个<div>容器,例如div1,div2,div3和div4。 我有两个用户:user1和user2。

我想在用户1访问该页面时显示div1和div3。 并在user2访问它时显示div2和div4。 我想使用AngularJS的ng-hideng-show指令。 我怎样才能做到这一点?

我会在某种用户访问对象的$ scope上设置属性,以便在加载用户时切换它们。

假设用户在控制器加载时加载它可能是这样的:

app.controller('SecuredForm', function($scope) {
     //get your user from where ever.
     var user = getSomeUser(); 

     // set your user permissions
     // here's some contrived example.
     $scope.permissions = {
         showAdmin: user.isRegistered && user.isAdmin,
         showBasic: user.isRegistered,
         showHelp: !user.isBanned
     }
});

在您的html中,您将使用这些范围项来设置显示或隐藏您的区域:

<div ng-show="permissions.showAdmin">
  <h3>Admin Area</h3>
  <!-- admin stuff here -->
</div>
<div ng-show="permissions.showBasic">
  <h3>Basic Info</h3>
  <!-- admin stuff here -->
</div>
<div ng-show="permissions.showHelp">
  <h3>Help</h3>
  <!-- help stuff here -->
</div>

有一点需要注意的是,ng-show和ng-hide根本就不显示HTML ... html仍在客户端上。 因此,请确保在您回拨服务器时需要权限来更改您在服务器上检查它们的内容 您不能认为用户有权仅仅因为表单可见而执行某些操作。 (你可能已经知道了,我只想彻底)。

为什么不给这个jsfiddle一个去。 更改$scope.userId变量,当您在jsFiddle点击“run”时,您将看到更新的更改。 代码:

HTML:

<div ng-app>
    <div ng-controller="DivGroup">
        <div ng-show="getUserId() == 1">Div 1</div>
        <div ng-show="getUserId() == 2">Div 2</div>
        <div ng-show="getUserId() == 1">Div 3</div>
        <div ng-show="getUserId() == 2">Div 4</div>       
    </div>
</div>

JavaScript的:

function DivGroup($scope) {

    $scope.userId = 2;

    $scope.getUserId = function() {
        console.log('test');
        return $scope.userId;             
    }
}

userId为1时,它显示一个和三个的内容,当它为2时,它显示两个和四个的内容。

这是真的:假,显示:隐藏逻辑对我来说非常好用,但它最适合用作切换。 http://geniuscarrier.com/ng-toggle-in-angularjs/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM