angularjs - Angular 指令 attrs.$observe

标签 angularjs directive

我在网上找到了这个 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/

相关文章:

javascript - 当我选择带有 Object 的选项时,"[object Object]"而不是 Object 被传递给 <select> 的 ng-model

javascript - 如何以 Angular 绑定(bind)对象中的嵌套列表

AngularJS : Listen for click events on a button outside of a directive

c# - 获取 "type or namespace name could not be found"但一切似乎都正常?

javascript - 如何从集合angularjs指令中获取值(value)

javascript - 无法使用 ng-repeat 循环遍历数组

javascript - 上传页面的一部分或页面中的一张图片 - 第一个(尽快)

javascript - Django-REST 和 AngularJS 中的变量名称

javascript - 如何将自定义指令绑定(bind)到所有输入元素?

angularjs - 如何在 angularJs 自定义指令中将值作为属性传递