Last active
December 21, 2015 06:39
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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