Angularjs: 'controller as syntax' and $watch

前端 未结 10 1595
抹茶落季
抹茶落季 2020-11-28 18:52

How to subscribe on property change when using controller as syntax?

controller(\'TestCtrl\', function ($         


        
10条回答
  •  青春惊慌失措
    2020-11-28 19:47

    Writing a $watch in ES6 syntax wasn't as easy as I expected. Here's what you can do:

    // Assuming
    // controllerAs: "ctrl"
    // or
    // ng-controller="MyCtrl as ctrl"
    export class MyCtrl {
      constructor ($scope) {
        'ngInject';
        this.foo = 10;
        // Option 1
        $scope.$watch('ctrl.foo', this.watchChanges());
        // Option 2
        $scope.$watch(() => this.foo, this.watchChanges());
      }
    
      watchChanges() {
        return (newValue, oldValue) => {
          console.log('new', newValue);
        }
      }
    }
    

提交回复
热议问题