2017-03-15 27 views
1

我創建了一個用戶配置文件,並希望顯示僅顯示配置文件所有者的編輯按鈕。我正在嘗試使用ng-if,以便從DOM中刪除編輯功能。如何使用ng-if顯示基於當前用戶的按鈕?

如何使用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; 
    } 
    } 
} 
+1

有什麼是好的,問題是你錯過'return' – George

回答

0

大家都提到的,函數沒有返回true或false。在添加回報後,我發現for語句是無關的,我只需要一個簡單的檢查。此代碼正常工作:

$scope.editProfile = function() { 
    if ($scope.user.id===$scope.currentUser.id) { 
    return true 
    } 
    return false 
} 
0

您正在返回從功能罷了。

你可以把它這樣

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

,並在控制器

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

只需添加

return canedit; 

下關閉托架

1

你的功能需求回覆轉truefalse

<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 
} 
相關問題