As I dive into learning and utilizing AngularJS, certain concepts still remain unclear to me.
Here is my query: within my application, there is a controller that utilizes $http
to fetch data from the backend upon initialization. Following a comprehensive tutorial from CodeSchool on Angular, I implemented the following structure:
app.controller("agentController", function ($http) {
var agentsCtrl = this;
agentsCtrl.agents = [];
$http.get("getAgents").success(function (data) {
agentsCtrl.agents = data;
});
...
HTML:
<div ng-controller="agentController as agentCtrl">
<div ng-repeat="agent in agentCtrl.agents">
...
This setup works well, but I question the necessity of declaring the controller as a variable within itself using this
. My understanding leads me to believe it's required so that I can reference it correctly within the $http
service, where the this
keyword would otherwise return an incorrect scope. Is my interpretation accurate?
I also discovered another approach which functions similarly:
app.controller("agentController", function ($http, $scope) {
$scope.agents = [];
$http.get("getAgents").success(function (data) {
$scope.agents = data;
});
HTML:
<div ng-controller="agentController as agentCtrl">
<div ng-repeat="agent in agents">
...
This alternative method appears to work because I explicitly inject the scope and use it within the service. Additionally, the HTML structure slightly differs. In the initial case, calling agentCtrl.agents
is necessary, while with scope, simply agents
suffices. This change stems from the fact that the variable is now declared on the scope rather than the controller. Is this assumption correct?
What would be considered best practice when encountering similar scenarios?
Your insights are greatly appreciated!