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

前端 未结 7 1133
广开言路
广开言路 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 10:01

    $watch object is available inside $scope object, so you need to add $scope inside your controller factory function & then place watcher over the variable.

    $scope.$watch(function(){
        return myBox.game;
    }, function(newVal){
       alert('Value changed to '+ newVal)
    });
    

    Demo Here

    Note: I know you had converted directive to component, to remove dependency of $scope so that you will get one step closer to Angular2. But it seems like it didn't get removed for this case.

    Update

    Basically angular 1.5 does added .component method jus differentiate two different functionality. Like component.stands to perform particular behaviby adding selector, where as directive stands to add specific behavior to DOM. Directive is just wrapper method on .directive DDO(Directive Definition Object). Only what you can see is, they had remove link/compile function while using .component method where you had an ability to get angular compiled DOM.

    Do use $onChanges/$doCheck lifecycle hook of Angular component lifecycle hook, those will be available after Angular 1.5.3+ version.

    $onChanges(changesObj) - Called whenever bindings are updated. The changesObj is a hash whose keys are the names of the bound properties.

    $doCheck() - Called on each turn of the digest cycle when binding changes. Provides an opportunity to detect and act on changes.

    By using same function inside component will ensure your code to be compatible to move to Angular 2.

    0 讨论(0)
提交回复
热议问题