【发布时间】:2014-02-20 03:11:06
【问题描述】:
我是 Angular 的新手,但仍在尝试了解它的工作原理和最佳实践。我的应用是一个使用 Angular 的单页 Rails 应用。
我正在开发一个用户可以关注/取消关注另一个用户的作品。根据后端的结构方式(使用 Mongo),追随者被嵌入到用户模型中。
我希望当用户点击关注时,它会发布一个 API 调用来关注用户,然后按钮从“关注”变为“取消关注”。我有使用 API 的关注和取消关注部分,只是不知道如何将按钮从关注切换到取消关注并在切换时返回。
由于从 User 模型中提取数据以构建个人资料页面,并且在 User 模型上没有发生关注/取消关注,我猜这就是绑定无法自动工作的原因。我已经通过增加/减少追随者数量并通过将用户推送到数组来将其添加到追随者来解决这个问题。
只需要有关在此处切换按钮的最佳做法的帮助。也可以在此处进行任何其他重构。
这是我目前得到的...
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"}})
]
谢谢!
【问题讨论】:
标签: ruby-on-rails angularjs angularjs-scope