I have been learning Angular and everything's been going smoothly. I have decided to try and incorporate TypeScript into this and wrote a small test controller in an already existing Angular/WebApi project I have been working on.
The controller "works" and initializes just fine, however, my $scope properties are not being updated when set to an HTTP promise. I have attached a "working" example of my issue using the TypeScript generated JS file. When debugging, I can see the then get triggered on the promise and the data I expected does return, but the page displays {}
Here is my actual TypeScript file.
/// <reference path="../../tds/angularjs/angular.d.ts" />
module RecordEditor {
export interface Scope extends ng.IScope{
tableId: any;
}
export class Controller {
$scope: Scope;
api : any;
constructor($scope: Scope, myApi: any) {
this.api = myApi;
this.$scope = $scope;
this.$scope.tableId = this.api.getTestResponse();
}
}
}
var app = angular.module("myApp");
app.controller("RecordEditor.Controller", ['$scope', 'myApi', RecordEditor.Controller]);
That controller is the only thing I have actually written in TypeScript. All the other controllers are in JavaScript and the same api I built returns responses just fine with those.
Below is the actual runnable snippet code with the JavaScript version of my Controller.
(function() {
var app = angular.module('myApp', []);
}());
(function() {
var myApi = function($http) {
var getTestResponse = function() {
// Hope it is okay to use SE API to test this question. Sorry if not.
return $http.get("https://api.stackexchange.com/2.2/sites")
.then(function(response) {
return "Hello!";
});
};
return {
getTestResponse: getTestResponse,
};
};
var module = angular.module("myApp");
module.service("myApi", ['$http', myApi]);
}());
var RecordEditor;
(function(RecordEditor) {
var Controller = (function() {
function Controller($scope, myApi) {
var _this = this;
this.api = myApi;
this.$scope = $scope;
this.$scope.response = this.api.getTestResponse();
this.$scope.ctorTest = 42;
}
return Controller;
})();
RecordEditor.Controller = Controller;
})(RecordEditor || (RecordEditor = {}));
var app = angular.module("myApp");
app.controller("RecordEditor.Controller", ['$scope', 'myApi', RecordEditor.Controller]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.min.js"></script>
<div ng-app="myApp" ng-controller="RecordEditor.Controller">
<div >
Scope property set in constructor: {{ctorTest}}
</div>
<div >
Scope response value: {{response}}
</div>
<div >
Scope response should have been "Hello!"
</div>
</div>
Can anyone actually tell me what I am doing wrong? Everything looks fine to me.
{}on page instead ofHello!). And that's calling a method on theapithat the other controllers can call just fine. I see your example has it working though. I am very lost right now.getTestResponse().then(...)please undelete your answer. It was correct.