Angular Directive attrs.$observe

后端 未结 2 550
盖世英雄少女心
盖世英雄少女心 2021-01-17 11:37

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 doi

相关标签:
2条回答
  • 2021-01-17 11:51

    In short:

    Everytime 'shareTwitterUrl' or 'shareTwitterText' changes, it will call the share function.

    From another stackoverflow answer: (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.

    From Angular docs: (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.

    0 讨论(0)
  • 2021-01-17 11:53
    <input type="text" ng-model="value" >
    <p sr = "_{{value}}_">sr </p>
    
    
    .directive('sr',function(){
    
    return {
    
            link: function(element, $scope, attrs){
                    attrs.$observe('sr', function() {
                                    console.log('change observe')
                        });
                }
        };
    })
    
    0 讨论(0)
提交回复
热议问题