Understanding how to effectively use Typescript and Angularjs in conjunction has been a challenge for me. Despite reading numerous blog posts and consulting the official documentation for both projects, the concepts just haven't fully clicked.
My Angular controller requires two dependencies: $scope and a custom service named greetingService. I have set up a main app Angular module where I have connected the controller and service. By including log statements in my Typescript constructors, I can verify that the dependencies are being injected correctly. However, when attempting to utilize a dependency within the controller, it appears as undefined. The code snippet below showcases this issue more clearly:
declare var angular;
module App.Services {
export class GreetingService {
constructor(private $http) {
console.log("In greeting service constructor");
console.log($http);
}
getGreetingsPromise() {
return this.$http.get('/greetings.json');
}
}
}
module App.Controllers {
export class GreetingController {
static $inject = ['$scope', 'greetingService'];
constructor(public $scope, public greetingService: App.Services.GreetingService) {
this.$scope.greeting = "This will be a greeting.";
this.$scope.greet = this.greet;
console.log(greetingService); // this is defined and looks right
}
greet(language: string) {
console.log("Greeting...");
console.log(this.$scope); // this is undefined
console.log(this.greetingService); // this is undefined
var greetingPromise = this.greetingService.getGreetingsPromise();
greetingPromise.then(data => this.$scope.greeting = data[language]);
}
}
}
var mainApp = angular.module('mainApp', []);
mainApp.controller('greetingController', ['$scope', 'greetingService', App.Controllers.GreetingController]);
mainApp.service('greetingService', App.Services.GreetingService);
Below is the Angular template (which displays "This will be a greeting" as intended from the constructor initialization):
<div class="jumbotron">
<div ng-controller="greetingController">
<p class="lead">{{greeting}}</p>
<button ng-click="greet('english')">Greet me</button>
</div>
</div>