如何使用带角度全栈生成器语法的$scope和$watch

How do I work with $scope and $watch with angular-fullstack generator syntax?

本文关键字:语法 scope watch 何使用 全栈      更新时间:2023-09-26

我正在使用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);
})();

我如何注入$watch,这样我就可以做一些类似的事情:

this.$watch('awasomeThings', function () { ... });

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

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

<body ng-controller="MyController as myCtl">
  <p ng-repeat="thing in myCtl.awesomeThings">{{thing}}</p>
</body>

仍然需要使用$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; 
  }
}

PS:这个语法很可能是ES6,但我可能错了。。。我用的是看起来很相似的打字本。