6

I am using the angular-fullstack generator to generate new routes for my application. The syntax is really unfamiliar and uses a class-like structure. How do I work with this to inject things like $scope and $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:

this.$watch('awasomeThings', function () { ... });
jOshT
  • 1,525
  • 1
  • 11
  • 15

1 Answers1

5

They are intending (my assumption) for you to use Angular's controllerAs syntax. When you do that, you end up using $scope a lot less (if at all).

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:

<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(). In this case, inject the $scope into your controller, the same way it's being done with $http above:

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.

Sunil D.
  • 17,983
  • 6
  • 53
  • 65
  • Perfect, thanks. It makes much more sense now. I think they are indeed using ES6 and [Babel](https://babeljs.io/) for compiling it to regular javacript. – jOshT Dec 23 '15 at 18:55
  • 1
    If you are using ES6, then you can declare your DI (for safe minification) also by inserting `static $inject = ['$scope'];` just under the class definition and before the constructor function. If your ES6 transpiler supports that static definition. – Sean Larkin Dec 23 '15 at 19:15