gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 05:22:05 24 4
gpt4 key购买 nike

我正在使用 angular-fullstack generator为我的应用程序生成新路由。语法是 really unfamiliar并使用类似类的结构。我如何使用它来注入(inject) $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);

})();

我如何注入(inject) $watch 以便我可以做类似的事情:

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

最佳答案

他们打算(我的假设)让您使用 Angular 的 controllerAs 语法。当您这样做时,您最终使用的 $scope 会少很多(如果有的话)。

原因是您的 View 不再直接绑定(bind)到作用域,它们绑定(bind)到 Controller 的属性。因此,在上面的 MyController 示例中, View 可以使用您提供的 Controller 名称访问 awesomeThings 数组:

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

您仍然需要使用 $scope 的一种情况是您想要使用 $scope.$watch()。在这种情况下,将 $scope 注入(inject)到您的 Controller 中,就像上面的 $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 但我可能是错的......我使用的 Typescript 看起来非常相似。

关于javascript - 我如何使用 $scope 和 $watch 使用 angular-fullstack 生成器语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34441026/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com