[英]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-hide
和ng-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.