Marco Marco - 4 months ago 47
AngularJS Question

Angular ng-show if in array

I have a ng-repeat for article comments, that looks like this:

<div ng-repeat="comment in comments">
<li class="item" ng-class-even="'even'">
<div class="row">
<div class="col">
<i class="icon ion-person"></i> {{ comment.user.first_name }} {{ comment.user.last_name }}
<i class="icon ion-record"></i> {{ comment.created_at }}
</div>
<!-- TODO: this needs to be an ng-if admin -->
<div ng-show="hasRole(comment.user)" class="col right">
<i class="icon ion-record admin"></i> Admin
</div>
</div>
<div class="row">
<div class="col">
<p>{{ comment.text }}</p>
</div>
</div>
</li>
</div>


I am trying to show this part only if the user is an admin:

<div ng-show="hasRole(comment.user)" class="col right">
<i class="icon ion-record admin"></i> Admin
</div>


I have tried to set that up following the answers here.

So I made a function in my controller:

$scope.hasRole = function(roleName) {
return $scope.comments.user.roles.indexOf(roleName) >= 0;
}


But it returns -1 every time, even when the user is an admin. My data looks like this:

1:Object
$$hashKey: "object:28"
article_id:"2"
created_at:"2016-05-12 12:19:05"
id:6
text:"someCommentText"
updated_at:null
user:Object
active:"1"
created_at:null
first_name:"admin"
id:1
last_name:"admin"
roles:Array[1]
0:Object
created_at:null
id:1
name:"Admin"
parent_id:null
pivot:Object
slug:"admin"

Answer

Use this in your HTML

<div ng-show="hasAdminRole(comment.user.roles)" class="col right">
    <i class="icon ion-record admin"></i> Admin
</div>

this is the method to determine that the user belongs to the admin role or not.

$scope.hasAdminRole = function(roles) {
    var isAdmin = false;
    for(var i = 0; i < roles.length; i++) {
        if (roles[i].name == 'Admin') {
            isAdmin = true;
            break;
        }
    }

    return isAdmin;
}