AngularJS 1.5+ Components do not support Watchers, what is the work around?

前端 未结 7 1300
广开言路
广开言路 2020-11-22 09:23

I\'ve been upgrading my custom directives to the new component architecture. I\'ve read that components do not support watchers. Is this correct? If so how do you detect cha

7条回答
  •  我在风中等你
    2020-11-22 09:38

    Available in IE11, MutationObserver https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver. You need to inject $element service into controller which semi-breaks DOM/controller separation, but I feel that this is a fundamental exception (ie. flaw) in angularjs. Since hide/show is async, we need on-show callback, that angularjs & angular-bootstrap-tab do not provide. It also requires that u know which specific DOM element u want to observe. I used following code for angularjs controller to trigger Highcharts chart reflow on-show.

    const myObserver = new MutationObserver(function (mutations) {
        const isVisible = $element.is(':visible') // Requires jquery
        if (!_.isEqual(isVisible, $element._prevIsVisible)) { // Lodash
            if (isVisible) {
                $scope.$broadcast('onReflowChart')
            }
            $element._prevIsVisible = isVisible
        }
    })
    myObserver.observe($element[0], {
        attributes: true,
        attributeFilter: ['class']
    })
    

提交回复
热议问题