如何使用 ng-if 显示基于当前用户的按钮?
How can I use ng-if to display a button based on the current user?
我正在创建一个用户个人资料,并希望显示一个仅对个人资料所有者显示的编辑按钮。我正在尝试使用 ng-if 以便从 DOM.
中删除编辑功能
如何使用 ng-if 显示基于当前用户的按钮?
在我看来:
<button ng-if="editProfile()">EDIT</button>
在我的控制器中:
$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;
}
}
}
您的函数没有返回任何内容。
你可以这样做
<button ng-if="canEdit()">EDIT</button>
并在您的控制器中
$scope.canEdit = function () {
return $scope.users.find(u=>u.id === $scope.currentUser.id) ? true : false;
}
只需添加
return canedit;
右括号下方
您的函数需要 return true
或 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
}
正如大家所提到的,函数不是 return 真或假。添加 return 后,我发现 for 语句是无关紧要的,我只需要一个简单的检查。此代码运行正常:
$scope.editProfile = function () {
if ($scope.user.id===$scope.currentUser.id) {
return true
}
return false
}
我正在创建一个用户个人资料,并希望显示一个仅对个人资料所有者显示的编辑按钮。我正在尝试使用 ng-if 以便从 DOM.
中删除编辑功能如何使用 ng-if 显示基于当前用户的按钮?
在我看来:
<button ng-if="editProfile()">EDIT</button>
在我的控制器中:
$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;
}
}
}
您的函数没有返回任何内容。
你可以这样做
<button ng-if="canEdit()">EDIT</button>
并在您的控制器中
$scope.canEdit = function () {
return $scope.users.find(u=>u.id === $scope.currentUser.id) ? true : false;
}
只需添加
return canedit;
右括号下方
您的函数需要 return true
或 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
}
正如大家所提到的,函数不是 return 真或假。添加 return 后,我发现 for 语句是无关紧要的,我只需要一个简单的检查。此代码运行正常:
$scope.editProfile = function () {
if ($scope.user.id===$scope.currentUser.id) {
return true
}
return false
}