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
4 Answers
Reset to default 2Your 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
}