我正在编写我的第一个打字稿控制器,并且在理解如何使用$ scope时遇到一些问题,以便我可以引用不同代码块中的元素。以下是相关代码:
module app.controllers {
class TeamsController implements app.domain.Team {
//properties
teamId: number;
teamName: string;
coach: app.domain.Coach;
division: app.domain.Division;
cheerleaderImage: string;
coachImage: string;
headerImage: string;
logoImage: string;
divisions: app.domain.Division[];
coaches: app.domain.Coach[];
teams: app.domain.Team[];
selectedTeam: app.domain.Team;
teamToBeUpdated: app.domain.Team;
httpService: ng.IHttpService;
static $inject = ['dataAccessService', '$http', '$scope'];
//constructor
constructor(private dataAccessService: app.common.DataAccessService, $http: ng.IHttpService, $scope: ng.IScope) {
this.teams = [];
this.divisions = [];
this.coaches = [];
this.httpService = $http;
var teamResource = dataAccessService.getTeamResource();
var divisionResource = dataAccessService.getDivisionResource();
var coachResource = dataAccessService.getCoachResource();
teamResource.query((data: app.domain.Team[]) => {
this.teams = data;
});
divisionResource.query((data: app.domain.Division[]) => {
this.divisions = data;
});
coachResource.query((data: app.domain.Coach[]) => {
this.coaches = data;
});
this.selectedTeam =
new app.domain.Team(0, "", new app.domain.Coach(0, ""), new app.domain.Division(0, ""), "", "", "", "");
this.teamToBeUpdated =
new app.domain.Team(0, "", new app.domain.Coach(0, ""), new app.domain.Division(0, ""), "", "", "", "");
}
addUpdateTeam(): void {
if (this.teamToBeUpdated.teamId === 0) {
//vm.isBusy = true;
//vm.errorMessage = "";
//post, pass teamToBeUpdated object
this.httpService.post('http://localhost:33201/api/Teams/Add', this.teamToBeUpdated)
.then(function (response) {
//success
this.teams.push(response.data);
this.teams.sort(function (a, b) {
if (a.teamName.toLowerCase() < b.teamName.toLowerCase()) return -1;
if (a.teamName.toLowerCase() > b.teamName.toLowerCase()) return 1;
return 0;
});
this.teamToBeUpdated =
new app.domain.Team(0, "", new app.domain.Coach(0, ""), new app.domain.Division(0, ""), "", "", "", ""); //clear form
}, function (error) {
//failure
//vm.errorMessage = "Failed to save new team: " + error;
})
.finally(function () {
//vm.isBusy = false;
});
}
}
}
//registration with module must be declared after class
angular.module("app")
.controller("teamsController", ['dataAccessService', '$http', '$scope', TeamsController]);
}
我在上面使用this
的地方,我想用$scope
替换它,但是当我尝试这样做时,我得到错误'{propertyname}在类型IScope上不存在'。
有人可以建议如何正确地做到这一点吗?
答案 0 :(得分:5)
您可以使用所需的属性创建扩展ng.IScope的界面。
interface TeamsScope extends ng.IScope {
teams: string[]
}
在构造函数中使用它代替ng.IScope。
constructor(private dataAccessService: app.common.DataAccessService, $http: ng.IHttpService, $scope: TeamsScope) {
只能通过此访问类中定义的所有属性。
例如,你可以在其中一个类方法中访问 $ scope :
this.$scope
为了在$ http服务的处理程序中保持相同的词法范围,您可以使用箭头功能。
this.httpService.post('http://localhost:33201/api/Teams/Add', this.teamToBeUpdated)
.then((response) => { this.teams = resonse.data});
您可以在此处找到有关arrow functions的更多信息。