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

前端 未结 7 1291
广开言路
广开言路 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:00

    Really Nice accepted answer, but I might add that you can use also the power of events ( a bit like in Qt signal / slots if you will ).

    An event is broadcast : $rootScope.$broadcast("clickRow", rowId) by any parent ( or even children controller ). Then in your controller you can handle the event like this :

    $scope.$on("clickRow", function(event, data){
        // do a refresh of the view with data == rowId
    });
    

    You can also add some logging on that like this ( taken from here : https://stackoverflow.com/a/34903433/3147071 )

    var withLogEvent = true; // set to false to avoid events logs
    app.config(function($provide) {
        if (withLogEvent)
        {
          $provide.decorator("$rootScope", function($delegate) {
            var Scope = $delegate.constructor;
            var origBroadcast = Scope.prototype.$broadcast;
            var origEmit = Scope.prototype.$emit;
    
            Scope.prototype.$broadcast = function() {
              console.log("$broadcast was called on $scope " + this.$id + " with arguments:",
                         arguments);
              return origBroadcast.apply(this, arguments);
            };
            Scope.prototype.$emit = function() {
              console.log("$emit was called on $scope " + this.$id + " with arguments:",
                         arguments);
              return origEmit.apply(this, arguments);
            };
            return $delegate;
          });
        }
    });
    

提交回复
热议问题