如何使用带角度全栈生成器语法的$scope和$watch
How do I work with $scope and $watch with angular-fullstack generator syntax?
我正在使用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,但我可能错了。。。我用的是看起来很相似的打字本。
相关文章:
- AngularJS:ng之后,重复$scope值未按预期更新
- 铬:“;未捕获的语法错误:意外的标记:"
- jQuery语法添加了var
- Javascript未捕获语法错误意外的标识符错误
- 为什么忽略了eval()代码中的语法错误
- 难以访问的JS环境中的语法错误
- 如何告诉MathJax对下标使用替代语法
- $ionicplatform内的$scope不;不起作用
- Javascript语法向设置发出sessionStorage值
- 未捕获的语法错误:意外的标记{
- 使用$scope方法时的ControllerAs语法
- AngularJS:使用$scope$以控制器作为语法进行观察
- 尝试理解$.inArray,或将$scope转换为“$scope”;控制器As”;AngularJS中的语法
- 使用不带$scope的$watch(作为语法的控制器)
- 使用 $scope.$apply 在 TypeScript 中使用控制器作为 vm 语法时
- AngularJS $scope和控制器作为语法真的没有区别吗?
- 如何使用带角度全栈生成器语法的$scope和$watch
- AngularJS-html中的scope变量语法
- 因果报应茉莉花和角度控制器使用'控制器为'语法(this而不是$scope)
- 使用ControllerAs语法绑定服务变量,不带$scope