Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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 () { ... });
like image 831
jOshT Avatar asked Dec 23 '15 17:12

jOshT


1 Answers

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.

like image 109
Sunil D. Avatar answered Nov 13 '22 15:11

Sunil D.