When using the syntax
<div ng-controller="BuildingsCtrl as bc">
to avoid using $scope
(as mentioned here), how should I incorporate $http
?
In other words, how can I refactor the following code without relying on $scope?
angular.module('atlasAngularApp')
.controller('BuildingsCtrl', function ($scope, $http) {
this.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
this.getBuildings = function () {
$http.get('http://localhost:40602/api/1.0/buildings')
.then(function successCallback(response) {
======> $scope.buildings = response.data;
}, function errorCallback(response) {
alert("Error");
}
);
}
});
To expand on this,
<li ng-repeat="thing in bc.awesomeThings">
{{ thing }}
</li>
Using this.awesomeThings
functions properly, allowing a view to utilize this
, but the following does not work:
angular.module('atlasAngularApp')
.controller('BuildingsCtrl', function ($http) {
var self = this;
this.getBuildings = function () {
$http.get('http://localhost:40602/api/1.0/buildings')
.then(function successCallback(response) {
======> self.buildings = response.data;
}, function errorCallback(response) {
alert("Error");
}
);
}
});
(note the self.buildings
part.)
I've experimented with various versions of this approach, but have yet to find a solution that works. This question is relevant, though my attempts to adapt it to my code have been unsuccessful.
It's worth mentioning that I don't have anything against $scope
; I'm simply trying to adhere to the Angular conventions endorsed by Yeoman-generated projects. Additionally, I'd appreciate an explanation of why $scope
may be viewed negatively.
As a reference, here is my view. Is there possibly an issue within it?
<div ng-controller="BuildingsCtrl as bc">
<table ng-init="buildings = bc.getBuildings()">
<tr ng-repeat="building in buildings">
<td>{{ building.name }}</td>
<td>{{ building.code }}</td>
<td>{{ building.image }}</td>
</tr>
</table>
</div>
The code functions correctly when employing $scope
.