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

I am using the angular -fullstack generator to create new routes for my application. The syntax is really unfamiliar and uses a class structure. How can I work with this to introduce things like $ scope and $ watch? The main thing I want to do is keep track of the change for a particular variable. The syntax is given below. Does anyone 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 can I add $ watch so that I can do something like:

 this.$watch('awasomeThings', function () { ... }); 
+6
source share
1 answer

They intend (my guess) to use the Angular controllerAs syntax. When you do this, you end up using $scope lot less (if at all).

The reason is that your views are no longer directly linked to the scope, they are bound to the properties of the controller. Therefore, in the MyController example above, views can access the awesomeThings array using the 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 $scope is when you want to use $scope.$watch() . In this case, enter $scope in your controller, just as you would 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.

+5
source

All Articles