Skip to content

Instantly share code, notes, and snippets.

@jhdavids8
Last active December 21, 2015 06:39
Show Gist options
  • Save jhdavids8/6265398 to your computer and use it in GitHub Desktop.
Save jhdavids8/6265398 to your computer and use it in GitHub Desktop.
Angular directive to dynamically render a follow or unfollow button, depending on whether we are already following the given user
angular.module("PathgatherApp").directive('pgFollowBtn', ["CurrentFollowedUsers", "$compile", (CurrentFollowedUsers, $compile) ->
restrict: 'A',
scope: {user: '=pgFollowBtn'},
link: (scope, element, attrs) ->
follow_btn = null
unfollow_btn = null
createFollowBtn = () ->
follow_btn = angular.element(
"<a href='javascript:void(0)' ng-disabled='submitting'>" +
"<span>Follow</span></a>"
)
$compile(follow_btn)(scope) # Compile the button so angular directives like ng-disabled work
element.append(follow_btn)
follow_btn.bind 'click', (e) ->
scope.submitting = true
CurrentFollowedUsers.follow(scope.user).then (response) ->
scope.submitting = false
follow_btn.remove()
createUnfollowBtn()
, (error) ->
scope.submitting = false
# alert an error, or whatever you want
scope.$apply()
createUnfollowBtn = () ->
unfollow_btn = angular.element(
"<a href='javascript:void(0)' ng-disabled='submitting'>" +
"<span>Unfollow</span></a>"
)
$compile(unfollow_btn)(scope)
element.append(unfollow_btn)
unfollow_btn.bind 'click', (e) ->
scope.submitting = true
CurrentFollowedUsers.unfollow(scope.user).then (response) ->
scope.submitting = false
unfollow_btn.remove()
createFollowBtn()
, (error) ->
scope.submitting = false
scope.$apply()
scope.$watch 'user', (val) ->
if scope.user
CurrentFollowedUsers.followingUser(scope.user).then (following_user) ->
if following_user then createUnfollowBtn() else createFollowBtn()
])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment