2014-02-20 26 views
0

我是Angular的新手,仍在嘗試瞭解它是如何工作的以及最佳實踐。我的應用程序是使用Angular的單頁Rails應用程序。API調用後的角度更新ng-show/ng-hide

我正在研究一個用戶可以關注/取消關注另一個用戶的作品。根據後端的結構(使用Mongo),追隨者被嵌入到用戶模型中。

我想要發生的事情是,當用戶點擊關注時,它發佈API調用以跟隨用戶,然後按鈕從「關注」更改爲「取消關注」。我有跟隨和取消關注的一塊與API的工作,只是不知道如何切換按鈕從關注到取消關注和返回時切換。

由於從用戶模型中拉取數據以構建配置文件頁面,並且在用戶模型上沒有發生關注/取消關注,所以我猜測這就是綁定不能自動工作的原因。我已經通過遞增/遞減跟隨者計數並將用戶推入到數組中來將其添加到追隨者中來實現它。

只需在這裏切換按鈕的最佳做法幫助。也可以在這裏打開任何其他的重構。

這是我走到這一步......

users_controller:

recipe.controller "UsersCtrl", ['$scope', '$routeParams', 'User', 'Follower', ($scope, $routeParams, User, Follower) -> 
    $scope.breadcrumb = $routeParams.id 
    $scope.current_user_name = window.current_user_name 
    $scope.user = User.get({id: $routeParams.id}) 
    $scope.addFollower = -> 
    newFollower = new Follower({user_id: $scope.current_user_name, follower_id: $routeParams.id}) 
    newFollower.$save() # Add success/failure 
    $scope.user.followers.push({username: $scope.current_user_name}) 
    $scope.user.follower_count += 1 
    $scope.removeFollower = -> 
    removeFollower = new Follower({user_id: $scope.current_user_name, follower_id: $routeParams.id}) 
    removeFollower.$delete() 
    $scope.user.follower_count -= 1 

    $scope.myProfile = -> 
    if $scope.current_user_name == $routeParams.id 
     return true 
    else 
     return false 
    $scope.followsUser = -> 
    in_followers($scope.user.followers, $scope.current_user_name) 

    in_followers = (array, username) -> 
    i = 0 
    while i < array.length 
     return (array[i].username is username) 
     i++ 
    false 
] 

profile.html.haml

%button{"ng-click" => "addFollower()", "ng-hide" => "myProfile(); followsUser()", :class => "btn btn-primary"} FOLLOW 
%button{"ng-click" => "removeFollower()", "ng-show" => "followsUser()", "ng-hide" => "myProfile()", :class => "btn btn-primary"} UNFOLLOW 

follower.js.coffee

recipe.factory 'Follower', ['$resource', ($resource) -> 
    Follower = $resource("/api/users/:user_id/follows", {user_id: "@user_id", follower_id: "@follower_id"}, 
    delete: {method: "DELETE", url: "/api/users/:user_id/follows/:follower_id", params: {user_id: "@user_id", follower_id: "@follower_id"}}) 
] 

謝謝!

回答

2

在你的控制器,你需要爲isFollowing添加值,並保持該更新,然後從你的UI /標記,你可以做的幾件事情之一,這裏有兩個:

有兩個按鈕,切換知名度

<button ng-show="isFollowing" ng-click="removeFollower()">Unfollow</button> 
<button ng-hide="isFollowing" ng-click="addFollower()">Follow</button> 

或者你可以使用一個按鍵改變按鈕的文本,並公開了新的功能,名爲setFollower它將調用要麼addFollower或內部removeFollower

<button ng-click="setFollower()">{{ isFollowing ? 'Unfollow' : 'Follow' }}</button> 
+0

謝謝。這非常有幫助。特別是關於如何實現單個按鈕的部分。我沒有想到這一點! – aressidi