简体   繁体   English

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

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

I am using the angular-fullstack generator to generate new routes for my application. 我正在使用angular-fullstack生成器为我的应用程序生成新路由。 The syntax is really unfamiliar and uses a class-like structure. 语法真的很陌生,并且使用类似于类的结构。 How do I work with this to inject things like $scope and $watch? 我如何使用它来注入$ scope和$ watch之类的东西? The main thing I want to do is watch for a change for a particular variable. 我想做的主要是观察特定变量的变化。 The syntax is below. 语法如下。 Anybody know how to work with this? 有谁知道如何使用它?

'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);

})();

How do I inject $watch so that I can do something like: 如何注入$ watch以便我可以执行以下操作:

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

They are intending (my assumption) for you to use Angular's controllerAs syntax. 他们打算(我的假设)让你使用Angular的controllerAs语法。 When you do that, you end up using $scope a lot less (if at all). 当你这样做时,你最终使用$scope (如果有的话)。

The reason is that your views no longer bind directly to the scope, they bind to properties of the controller. 原因是您的视图不再直接绑定到范围,它们绑定到控制器的属性。 So in your MyController example above, the views can access the array of awesomeThings using a name for the controller that you supply: 因此,在上面的MyController示例中,视图可以使用您提供的控制器的名称访问awesomeThings数组:

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

One case where you still need to use the $scope is when you want to use $scope.$watch() . 你仍然需要使用$scope一种情况是你想使用$scope.$watch() In this case, inject the $scope into your controller, the same way it's being done with $http above: 在这种情况下,将$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: This syntax is most likely ES6 but I could be wrong ... I use Typescript which looks very similar. PS:这种语法很可能是ES6,但我可能错了......我使用看起来非常相似的Typescript。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM