我正在嘗試使用打字稿來編寫angularjs,但我現在被卡住了。我有一個名爲AgeService的服務。該服務有一個名爲calculateAge的函數。即時通訊調用它到我的控制器,但我得到一個錯誤寫在下面。如何在控制器中使用角度服務 - TypeScript
SERVICE.TS
var servicesModule = angular.module('services', []);
class AgeService {
static AngularDependency = [AgeService];
constructor(private $scope: ng.IScope) {
}
public calculateAge(birthdate: string) {
var today = new Date();
var dob = new Date(Date.parse(birthdate));
var years = today.getFullYear() - dob.getFullYear();
if (today.getMonth() < dob.getMonth() || (today.getMonth() == dob.getMonth() && today.getDate() < dob.getDate()))
years -= 1;
return years;
}
}
servicesModule.service('ageService', AgeService.AngularDependency)
CONTROLLER.TS
var controllersModule = angular.module('controllers', []);
class PersonController {
static AngularDependency = ['$scope', PersonController, 'ageService'];
constructor(private $scope: PersonScope, private ageService: AgeService) {
this.initController();
}
private initController() {
this.$scope.name = 'Berkin';
this.$scope.person = {
name: 'Berkin',
dob: '25-06-1995'
};
this.$scope.person.age = this.ageService.calculateAge(this.$scope.person.dob);
}
}
controllersModule.controller('personController', PersonController.AngularDependency);
HTML
<h4 ng-controller="personController">{{name}} {{person.age}}</h4>
ERROR
謝謝...
爲什麼你在角2中使用角1? –
我猜他沒有在角度2中使用角度1;它的角1只是寫在TS中,他應該最終在他的index.html – Rahul
中引用.js文件爲什麼'PersonController.AngularDependency'只有'PersonController'應該正常工作? – Rahul