I found this Angular Directive online to add a twitter share button. It all seems staright forward but I can't work out what the attrs.$observe
is actually doing.
I have looked in the docs but can't see $observe
referenced anywhere.
The directive just seems to add the href
which would come from the controller so can anyone explain what the rest of the code is doing?
module.directive('shareTwitter', ['$window', function($window) {
return {
restrict: 'A',
link: function($scope, element, attrs) {
$scope.share = function() {
var href = 'https://twitter.com/share';
$scope.url = attrs.shareUrl || $window.location.href;
$scope.text = attrs.shareText || false;
href += '?url=' + encodeURIComponent($scope.url);
if($scope.text) {
href += '&text=' + encodeURIComponent($scope.text);
}
element.attr('href', href);
}
$scope.share();
attrs.$observe('shareUrl', function() {
$scope.share();
});
attrs.$observe('shareText', function() {
$scope.share();
});
}
}
}]);
<a href="" target="_blank" share-twitter share-url="[[shareTwitterUrl]]" share-text="[[shareTwitterText]]">Twitter</a>