Is there a way to watch attribute changes triggered from outside the AngularJS world?

后端 未结 2 970
情话喂你
情话喂你 2020-12-18 01:49

I’m trying to understand interactions between the Angular world and the non-Angular world.

Given a directive that one declares like this:



        
2条回答
  •  醉酒成梦
    2020-12-18 02:20

    Use a Web Components library like x-tags by Mozilla or Polymer by Google. This option works without maunally calling $scope.$apply every time the attribute changes.

    I use x-tags because of their wider browser support. While defining a new custom tag (directive) you can set the option lifecycle.attributeChanged to a callback function, which will fire every time an argument is changed.

    The official docs aren't very helpful. But by trial and error and diving into the code I managed to find out how it works.

    The callback function's context (the this object) is the element itself. The one whose attribute has changed. The callback can take three arguments:

    • name – the name of the attribute,
    • oldValue and
    • newValue – these speak for themselves.

    So now, down to business:

    The code

    This will watch the attribute for changes:

    xtag.register('dir1', {
        lifecycle: {
            attributeChanged: function (attribute, changedFrom, changedTo) {
                // Find the element's scope
                var scope = angular.element(this).scope();
    
                // Update the scope if our attribute has changed
                scope.$apply(function () {
                    if (attribute == 'attr1') scope.style = changedTo;
                });
            }
        }
    });
    

    The attributeChanged callback only fires when the arguments' values actually change. To get their initial values you need to scan the lot manually. The easiest way seems to be while defining the directive:

    myApp.directive('dir1', function () {
        return {
            ... ,
            link: function (scope, element, attributes) {
                scope.attr1 = element[0].getAttribute('attr1');
            }
        };
    });
    

提交回复
热议问题