如何使用angular-fullstack生成器语法使用$ scope和$ watch?

jOs*_*shT 6 javascript angularjs mean-stack meanjs angular-fullstack

我正在使用angular-fullstack生成器为我的应用程序生成新的路由.语法真的很陌生,并且使用类似于类的结构.我如何使用它来注入$ scope和$ watch之类的东西?我想做的主要是观察特定变量的变化.语法如下.有谁知道如何使用它?

'use strict';

(function() {

class MainController {

  constructor($http) {
    this.$http = $http;
    this.awesomeThings = [];

    $http.get('/api/things').then(response => {
      this.awesomeThings = response.data;
    });
  }

  addThing() {
    if (this.newThing) {
      this.$http.post('/api/things', { name: this.newThing });
      this.newThing = '';
    }
  }

  deleteThing(thing) {
    this.$http.delete('/api/things/' + thing._id);
  }
}

angular.module('myapp')
  .controller('MainController', MainController);

})();
Run Code Online (Sandbox Code Playgroud)

如何注入$ watch以便我可以执行以下操作:

this.$watch('awasomeThings', function () { ... });
Run Code Online (Sandbox Code Playgroud)

Sun*_* D. 5

他们打算(我的假设)让你使用Angular的controllerAs语法.当你这样做时,你最终会$scope少用(如果有的话).

原因是您的视图不再直接绑定到范围,它们绑定到控制器的属性.因此,在MyController上面的示例中,视图可以awesomeThings使用您提供的控制器的名称访问数组:

<body ng-controller="MyController as myCtl">
  <p ng-repeat="thing in myCtl.awesomeThings">{{thing}}</p>
</body>
Run Code Online (Sandbox Code Playgroud)

您仍然需要使用的一种情况$scope是您想要使用的情况$scope.$watch().在这种情况下,将其$scope注入您的控制器,就像$http上面所做的一样:

class MyController {

  constructor($scope) {
    // use the $scope.$watch here or keep a reference to it so you can
    // call $scope.$watch from a method
    this.$scope = $scope; 
  }

}
Run Code Online (Sandbox Code Playgroud)

PS:这种语法很可能是ES6,但我可能错了......我使用看起来非常相似的Typescript.