我在网上找到了这个 Angular 指令来添加 Twitter 分享按钮。这一切看起来都很简单,但我无法弄清楚 attrs.$observe
实际上在做什么。
我查看了文档,但看不到任何地方引用的 $observe
。
该指令似乎只是添加了来自 Controller 的 href
,所以有人可以解释其余代码在做什么吗?
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>
最佳答案
简而言之:
每次“shareTwitterUrl”或“shareTwitterText”发生变化时,都会调用分享函数。
来自另一个 stackoverflow 答案: ( https://stackoverflow.com/a/14907826/2874153 )
$observe() is a method on the Attributes object, and as such, it can only be used to observe/watch the value change of a DOM attribute. It is only used/called inside directives. Use $observe when you need to observe/watch a DOM attribute that contains interpolation (i.e., {{}}'s). E.g., attr1="Name: {{name}}", then in a directive: attrs.$observe('attr1', ...). (If you try scope.$watch(attrs.attr1, ...) it won't work because of the {{}}s -- you'll get undefined.) Use $watch for everything else.
来自 Angular 文档: ( http://docs.angularjs.org/api/ng/type/$compile.directive.Attributes )
$compile.directive.Attributes#$observe(key, fn);
Observes an interpolated attribute.
The observer function will be invoked once during the next $digest fol lowing compilation. The observer is then invoked whenever the interpolated value changes.
关于angularjs - Angular 指令 attrs.$observe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21929794/