最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I use ng-if to display a button based on the current user? - Stack Overflow

programmeradmin0浏览0评论

I am create a user profile and would like to show an edit button that only displays for the profile's owner. I am attempting to use ng-if so that the edit capabilities are removed from the DOM.

How can I use ng-if to display a button based on the current user?

In my view:

<button ng-if="editProfile()">EDIT</button>

In my controller:

$scope.editProfile = function (canedit) {
  var canedit = false;
  for (var i=0;i<$scope.users.length;i++) {
    if ($scope.users[i].id===$scope.currentUser.id) {
      canedit = true;
     }
  }
}

I am create a user profile and would like to show an edit button that only displays for the profile's owner. I am attempting to use ng-if so that the edit capabilities are removed from the DOM.

How can I use ng-if to display a button based on the current user?

In my view:

<button ng-if="editProfile()">EDIT</button>

In my controller:

$scope.editProfile = function (canedit) {
  var canedit = false;
  for (var i=0;i<$scope.users.length;i++) {
    if ($scope.users[i].id===$scope.currentUser.id) {
      canedit = true;
     }
  }
}
Share Improve this question asked Mar 15, 2017 at 15:09 thischrishallthischrishall 872 gold badges2 silver badges9 bronze badges 1
  • 1 What's there is fine, the problem is you're missing the return – George Commented Mar 15, 2017 at 15:10
Add a ment  | 

4 Answers 4

Reset to default 2

Your function needs to return true or false

<button ng-if="editProfile()">EDIT</button>


$scope.editProfile = function () {
  for (var i=0;i<$scope.users.length;i++) {
    if ($scope.users[i].id===$scope.currentUser.id) {
      return true
     }
  }
  return false
}

You are returning nothing from your function.

You can make it this way

<button ng-if="canEdit()">EDIT</button>

and in your controller

$scope.canEdit = function () {
    return $scope.users.find(u=>u.id === $scope.currentUser.id) ? true : false;
}

Just add

return canedit;

below the for closing bracket

As everyone mentioned, the function wasn't returning true or false. After adding the return I discovered that the for statement was extraneous and I just needed a simple check. This code is working correctly:

$scope.editProfile = function () {
  if ($scope.user.id===$scope.currentUser.id) {
    return true
  }
   return false
 }
发布评论

评论列表(0)

  1. 暂无评论