简体   繁体   中英

Evaluating an expression in AngularJS ng-show directive

Background: As part of a project I'm working on, Users (referred to as "artists" in the case below) can optionally select one or more from a series of Roles: Manager, Producer, Agent, and so forth. Consequently, I need to show or hide certain parts of page depending on which Role(s) the User has selected.

The example: I've tried using the following to conditionally show a div when the User has selected "Manager" as one of his/her Roles (and have it hidden when "Manager" isn't selected), but with no luck. What should I be using in the ng-show directive instead?

<div class="manager_section" ng-show="data.artist.roles.name == 'Manager'">Sample Text Here</div>

Please note: the div appears just fine with no ng-show/ng-hide directive applied, so I'm not looking for a CSS answer or anything; I'm simply looking for the conditional aspect provided by ng-show/ng-hide. And I know the data for the Roles is being pulled to the page, because when I ran the following on the page to test it, the names of each of the Roles the User had selected were accurately displayed:

<div ng-repeat="role in data.artist.roles">{{ role.name }}</div>

You can use controller method if you need to run arbitrary JavaScript code.

For example:

<div class="manager_section" ng-show="isAuthorized('Manager')">Sample Text Here</div>

angular.module('myApp', [])
                 .controller('AppCtrl',function(){
                    $scope.isAuthorized = function(role){
                        for(var i=0;i<$scope.data.artist.roles.length;i++){
                           if($scope.data.artist.roles[i].name === role) return true;
                        }
                        return false;
                    }
                 };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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