角度需要重新加载页面以显示fb共享按钮

时间:2021-12-29 19:00:49

I am trying to get facebooks share plugin up and running. The problem i have been running into is that I have to reload the page to actually get the share button to show up. If i navigate to the page through link or url the facebook share button will not show up, i have to reload the page and then the button will show up. I am using angular so thought to use a directive but so far my efforts have not been successful.

我想让facebook分享插件并运行。我遇到的问题是我必须重新加载页面以实际显示共享按钮。如果我通过链接或网址导航到页面,Facebook分享按钮将不会显示,我必须重新加载页面,然后按钮将显示。我正在使用角度因此想到使用指令,但到目前为止我的努力还没有成功。

here is where I have the directive in my template

这是我在模板中有指令的地方

<div class="fb-share-button" fb-share data-href="{{fbUrl}}" data-layout="button" id='fb-share'></div>

here is my directive.

这是我的指示。

angular.module('App').directive('fbShare', function () {
    function createHTML(href, layout) {
        return '<div class="fb-share-button" ' +
                       'data-href="' + href + '" ' +
                       'data-layout="' + layout + '" ' +
               '</div>';
    }

    return {
        restrict: 'A',
        scope: {},
        link: function postLink(scope, elem, attrs) {
        attrs.$observe('dataHref', function (newValue) {
                var href        = newValue;
                var layout    = attrs.layout    || 'button';

                elem.html(createHTML(href, layout));
                FB.XFBML.parse(elem[0]);
            });
        }
    };
});

the facebook sdk code which is just after the opening body tag

facebook sdk代码就在开放的body标签之后

  <div id="fb-root"></div>
  <script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.5&appId=xxxxxxxxxx";
  fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'facebook-jssdk'));
  </script>

1 个解决方案

#1


7  

Here is a great set of directives for Angular sharing widgets including FB: http://plnkr.co/edit/OvZRK6?p=preview

以下是Angular共享小部件的一组很好的指令,包括FB:http://plnkr.co/edit/OvZRK6?p = preview

Just set your FB APP ID and user a scope variable for your url, imageURl and Name.

只需为您的URL,imageURl和Name设置您的FB APP ID和用户范围变量。

If you view his code you can see how to render the code and possibly customize the FB template to your needs.

如果您查看他的代码,您可以看到如何呈现代码并可能根据您的需要自定义FB模板。

angular.module('myApp', ['angulike'])
  .run([
    '$rootScope',
    function($rootScope) {
      $rootScope.facebookAppId = '85024842290'; // set your facebook app id here
    }
  ]);

angular.module('myApp')
  .controller('myController', [
    '$scope',
    function($scope) {
      $scope.myModel = {
        Url: 'http://jasonwatmore.com/post/2014/08/01/AngularJS-directives-for-social-sharing-buttons-Facebook-Like-GooglePlus-Twitter-and-Pinterest.aspx',
        Name: "AngularJS directives for social sharing buttons - Facebook, Google+, Twitter and Pinterest | Jason Watmore's Blog",
        ImageUrl: 'http://www.jasonwatmore.com/pics/jason.jpg'
      };
    }
  ]);


/**
 * AngularJS directives for social sharing buttons - Facebook Like, Google+, Twitter and Pinterest
 * @author Jason Watmore <jason@pointblankdevelopment.com.au> (http://jasonwatmore.com)
 * @version 1.2.0
 */
(function() {
  angular.module('angulike', [])

  .directive('fbLike', [
    '$window', '$rootScope',
    function($window, $rootScope) {
      return {
        restrict: 'A',
        scope: {
          fbLike: '=?'
        },
        link: function(scope, element, attrs) {
          if (!$window.FB) {
            // Load Facebook SDK if not already loaded
            $.getScript('//connect.facebook.net/en_US/sdk.js', function() {
              $window.FB.init({
                appId: '85024842290',
                xfbml: true,
                version: 'v2.0'
              });
              renderLikeButton();
            });
          } else {
            renderLikeButton();
          }

          var watchAdded = false;

          function renderLikeButton() {
            if (!!attrs.fbLike && !scope.fbLike && !watchAdded) {
              // wait for data if it hasn't loaded yet
              watchAdded = true;
              var unbindWatch = scope.$watch('fbLike', function(newValue, oldValue) {
                if (newValue) {
                  renderLikeButton();

                  // only need to run once
                  unbindWatch();
                }

              });
              return;
            } else {
              element.html('<div class="fb-like"' + (!!scope.fbLike ? ' data-href="' + scope.fbLike + '"' : '') + ' data-layout="button_count" data-action="like" data-show-faces="true" data-share="true"></div>');
              $window.FB.XFBML.parse(element.parent()[0]);
            }
          }
        }
      };
    }
  ])

  .directive('googlePlus', [
    '$window',
    function($window) {
      return {
        restrict: 'A',
        scope: {
          googlePlus: '=?'
        },
        link: function(scope, element, attrs) {
          if (!$window.gapi) {
            // Load Google SDK if not already loaded
            $.getScript('//apis.google.com/js/platform.js', function() {
              renderPlusButton();
            });
          } else {
            renderPlusButton();
          }

          var watchAdded = false;

          function renderPlusButton() {
            if (!!attrs.googlePlus && !scope.googlePlus && !watchAdded) {
              // wait for data if it hasn't loaded yet
              watchAdded = true;
              var unbindWatch = scope.$watch('googlePlus', function(newValue, oldValue) {
                if (newValue) {
                  renderPlusButton();

                  // only need to run once
                  unbindWatch();
                }

              });
              return;
            } else {
              element.html('<div class="g-plusone"' + (!!scope.googlePlus ? ' data-href="' + scope.googlePlus + '"' : '') + ' data-size="medium"></div>');
              $window.gapi.plusone.go(element.parent()[0]);
            }
          }
        }
      };
    }
  ])

  .directive('tweet', [
    '$window', '$location',
    function($window, $location) {
      return {
        restrict: 'A',
        scope: {
          tweet: '=',
          tweetUrl: '='
        },
        link: function(scope, element, attrs) {
          if (!$window.twttr) {
            // Load Twitter SDK if not already loaded
            $.getScript('//platform.twitter.com/widgets.js', function() {
              renderTweetButton();
            });
          } else {
            renderTweetButton();
          }

          var watchAdded = false;

          function renderTweetButton() {
            if (!scope.tweet && !watchAdded) {
              // wait for data if it hasn't loaded yet
              watchAdded = true;
              var unbindWatch = scope.$watch('tweet', function(newValue, oldValue) {
                if (newValue) {
                  renderTweetButton();

                  // only need to run once
                  unbindWatch();
                }
              });
              return;
            } else {
              element.html('<a href="https://twitter.com/share" class="twitter-share-button" data-text="' + scope.tweet + '" data-url="' + (scope.tweetUrl || $location.absUrl()) + '">Tweet</a>');
              $window.twttr.widgets.load(element.parent()[0]);
            }
          }
        }
      };
    }
  ])

  .directive('pinIt', [
    '$window', '$location',
    function($window, $location) {
      return {
        restrict: 'A',
        scope: {
          pinIt: '=',
          pinItImage: '=',
          pinItUrl: '='
        },
        link: function(scope, element, attrs) {
          if (!$window.parsePins) {
            // Load Pinterest SDK if not already loaded
            (function(d) {
              var f = d.getElementsByTagName('SCRIPT')[0],
                p = d.createElement('SCRIPT');
              p.type = 'text/javascript';
              p.async = true;
              p.src = '//assets.pinterest.com/js/pinit.js';
              p['data-pin-build'] = 'parsePins';
              p.onload = function() {
                if (!!$window.parsePins) {
                  renderPinItButton();
                } else {
                  setTimeout(p.onload, 100);
                }
              };
              f.parentNode.insertBefore(p, f);
            }($window.document));
          } else {
            renderPinItButton();
          }

          var watchAdded = false;

          function renderPinItButton() {
            if (!scope.pinIt && !watchAdded) {
              // wait for data if it hasn't loaded yet
              watchAdded = true;
              var unbindWatch = scope.$watch('pinIt', function(newValue, oldValue) {
                if (newValue) {
                  renderPinItButton();

                  // only need to run once
                  unbindWatch();
                }
              });
              return;
            } else {
              element.html('<a href="//www.pinterest.com/pin/create/button/?url=' + (scope.pinItUrl || $location.absUrl()) + '&media=' + scope.pinItImage + '&description=' + scope.pinIt + '" data-pin-do="buttonPin" data-pin-config="beside"></a>');
              $window.parsePins(element.parent()[0]);
            }
          }
        }
      };
    }
  ]);

})();
<!DOCTYPE html>
<html ng-app="myApp">

<head>
  <meta charset="utf-8" />
  <title>AngularJS directives for social sharing buttons - Facebook Like, Google+, Twitter and Pinterest</title>
  <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
</head>

<body>
  <div ng-controller="myController" class="jumbotron text-center">
    <div class="container">
      <div fb-like></div>
      <div class="col-xs-3">
        <div fb-like="myModel.Url"></div>
      </div>
      <div class="col-xs-3">
        <div tweet="myModel.Name" tweet-url="myModel.Url"></div>
      </div>
      <div class="col-xs-3">
        <div google-plus="myModel.Url"></div>
      </div>
      <div class="col-xs-3">
        <div pin-it="myModel.Name" pin-it-image="myModel.ImageUrl" pin-it-url="myModel.Url"></div>
      </div>
    </div>
  </div>
  <div class="credits text-center">
    <p>
      <a href="http://www.jasonwatmore.com/post/2014/08/01/AngularJS-directives-for-social-sharing-buttons-Facebook-Like-GooglePlus-Twitter-and-Pinterest.aspx">AngularJS directives for social sharing buttons</a>
    </p>
    <p>
      <a href="http://www.jasonwatmore.com">www.jasonwatmore.com</a>
    </p>
  </div>
  <script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
  <script src="https://code.angularjs.org/1.2.16/angular.js"></script>
  <script src="angulike.js"></script>
  <script src="app.js"></script>
</body>

</html>

#1


7  

Here is a great set of directives for Angular sharing widgets including FB: http://plnkr.co/edit/OvZRK6?p=preview

以下是Angular共享小部件的一组很好的指令,包括FB:http://plnkr.co/edit/OvZRK6?p = preview

Just set your FB APP ID and user a scope variable for your url, imageURl and Name.

只需为您的URL,imageURl和Name设置您的FB APP ID和用户范围变量。

If you view his code you can see how to render the code and possibly customize the FB template to your needs.

如果您查看他的代码,您可以看到如何呈现代码并可能根据您的需要自定义FB模板。

angular.module('myApp', ['angulike'])
  .run([
    '$rootScope',
    function($rootScope) {
      $rootScope.facebookAppId = '85024842290'; // set your facebook app id here
    }
  ]);

angular.module('myApp')
  .controller('myController', [
    '$scope',
    function($scope) {
      $scope.myModel = {
        Url: 'http://jasonwatmore.com/post/2014/08/01/AngularJS-directives-for-social-sharing-buttons-Facebook-Like-GooglePlus-Twitter-and-Pinterest.aspx',
        Name: "AngularJS directives for social sharing buttons - Facebook, Google+, Twitter and Pinterest | Jason Watmore's Blog",
        ImageUrl: 'http://www.jasonwatmore.com/pics/jason.jpg'
      };
    }
  ]);


/**
 * AngularJS directives for social sharing buttons - Facebook Like, Google+, Twitter and Pinterest
 * @author Jason Watmore <jason@pointblankdevelopment.com.au> (http://jasonwatmore.com)
 * @version 1.2.0
 */
(function() {
  angular.module('angulike', [])

  .directive('fbLike', [
    '$window', '$rootScope',
    function($window, $rootScope) {
      return {
        restrict: 'A',
        scope: {
          fbLike: '=?'
        },
        link: function(scope, element, attrs) {
          if (!$window.FB) {
            // Load Facebook SDK if not already loaded
            $.getScript('//connect.facebook.net/en_US/sdk.js', function() {
              $window.FB.init({
                appId: '85024842290',
                xfbml: true,
                version: 'v2.0'
              });
              renderLikeButton();
            });
          } else {
            renderLikeButton();
          }

          var watchAdded = false;

          function renderLikeButton() {
            if (!!attrs.fbLike && !scope.fbLike && !watchAdded) {
              // wait for data if it hasn't loaded yet
              watchAdded = true;
              var unbindWatch = scope.$watch('fbLike', function(newValue, oldValue) {
                if (newValue) {
                  renderLikeButton();

                  // only need to run once
                  unbindWatch();
                }

              });
              return;
            } else {
              element.html('<div class="fb-like"' + (!!scope.fbLike ? ' data-href="' + scope.fbLike + '"' : '') + ' data-layout="button_count" data-action="like" data-show-faces="true" data-share="true"></div>');
              $window.FB.XFBML.parse(element.parent()[0]);
            }
          }
        }
      };
    }
  ])

  .directive('googlePlus', [
    '$window',
    function($window) {
      return {
        restrict: 'A',
        scope: {
          googlePlus: '=?'
        },
        link: function(scope, element, attrs) {
          if (!$window.gapi) {
            // Load Google SDK if not already loaded
            $.getScript('//apis.google.com/js/platform.js', function() {
              renderPlusButton();
            });
          } else {
            renderPlusButton();
          }

          var watchAdded = false;

          function renderPlusButton() {
            if (!!attrs.googlePlus && !scope.googlePlus && !watchAdded) {
              // wait for data if it hasn't loaded yet
              watchAdded = true;
              var unbindWatch = scope.$watch('googlePlus', function(newValue, oldValue) {
                if (newValue) {
                  renderPlusButton();

                  // only need to run once
                  unbindWatch();
                }

              });
              return;
            } else {
              element.html('<div class="g-plusone"' + (!!scope.googlePlus ? ' data-href="' + scope.googlePlus + '"' : '') + ' data-size="medium"></div>');
              $window.gapi.plusone.go(element.parent()[0]);
            }
          }
        }
      };
    }
  ])

  .directive('tweet', [
    '$window', '$location',
    function($window, $location) {
      return {
        restrict: 'A',
        scope: {
          tweet: '=',
          tweetUrl: '='
        },
        link: function(scope, element, attrs) {
          if (!$window.twttr) {
            // Load Twitter SDK if not already loaded
            $.getScript('//platform.twitter.com/widgets.js', function() {
              renderTweetButton();
            });
          } else {
            renderTweetButton();
          }

          var watchAdded = false;

          function renderTweetButton() {
            if (!scope.tweet && !watchAdded) {
              // wait for data if it hasn't loaded yet
              watchAdded = true;
              var unbindWatch = scope.$watch('tweet', function(newValue, oldValue) {
                if (newValue) {
                  renderTweetButton();

                  // only need to run once
                  unbindWatch();
                }
              });
              return;
            } else {
              element.html('<a href="https://twitter.com/share" class="twitter-share-button" data-text="' + scope.tweet + '" data-url="' + (scope.tweetUrl || $location.absUrl()) + '">Tweet</a>');
              $window.twttr.widgets.load(element.parent()[0]);
            }
          }
        }
      };
    }
  ])

  .directive('pinIt', [
    '$window', '$location',
    function($window, $location) {
      return {
        restrict: 'A',
        scope: {
          pinIt: '=',
          pinItImage: '=',
          pinItUrl: '='
        },
        link: function(scope, element, attrs) {
          if (!$window.parsePins) {
            // Load Pinterest SDK if not already loaded
            (function(d) {
              var f = d.getElementsByTagName('SCRIPT')[0],
                p = d.createElement('SCRIPT');
              p.type = 'text/javascript';
              p.async = true;
              p.src = '//assets.pinterest.com/js/pinit.js';
              p['data-pin-build'] = 'parsePins';
              p.onload = function() {
                if (!!$window.parsePins) {
                  renderPinItButton();
                } else {
                  setTimeout(p.onload, 100);
                }
              };
              f.parentNode.insertBefore(p, f);
            }($window.document));
          } else {
            renderPinItButton();
          }

          var watchAdded = false;

          function renderPinItButton() {
            if (!scope.pinIt && !watchAdded) {
              // wait for data if it hasn't loaded yet
              watchAdded = true;
              var unbindWatch = scope.$watch('pinIt', function(newValue, oldValue) {
                if (newValue) {
                  renderPinItButton();

                  // only need to run once
                  unbindWatch();
                }
              });
              return;
            } else {
              element.html('<a href="//www.pinterest.com/pin/create/button/?url=' + (scope.pinItUrl || $location.absUrl()) + '&media=' + scope.pinItImage + '&description=' + scope.pinIt + '" data-pin-do="buttonPin" data-pin-config="beside"></a>');
              $window.parsePins(element.parent()[0]);
            }
          }
        }
      };
    }
  ]);

})();
<!DOCTYPE html>
<html ng-app="myApp">

<head>
  <meta charset="utf-8" />
  <title>AngularJS directives for social sharing buttons - Facebook Like, Google+, Twitter and Pinterest</title>
  <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
</head>

<body>
  <div ng-controller="myController" class="jumbotron text-center">
    <div class="container">
      <div fb-like></div>
      <div class="col-xs-3">
        <div fb-like="myModel.Url"></div>
      </div>
      <div class="col-xs-3">
        <div tweet="myModel.Name" tweet-url="myModel.Url"></div>
      </div>
      <div class="col-xs-3">
        <div google-plus="myModel.Url"></div>
      </div>
      <div class="col-xs-3">
        <div pin-it="myModel.Name" pin-it-image="myModel.ImageUrl" pin-it-url="myModel.Url"></div>
      </div>
    </div>
  </div>
  <div class="credits text-center">
    <p>
      <a href="http://www.jasonwatmore.com/post/2014/08/01/AngularJS-directives-for-social-sharing-buttons-Facebook-Like-GooglePlus-Twitter-and-Pinterest.aspx">AngularJS directives for social sharing buttons</a>
    </p>
    <p>
      <a href="http://www.jasonwatmore.com">www.jasonwatmore.com</a>
    </p>
  </div>
  <script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
  <script src="https://code.angularjs.org/1.2.16/angular.js"></script>
  <script src="angulike.js"></script>
  <script src="app.js"></script>
</body>

</html>