Attempting to give this question a precise title as possible, I find myself struggling with an issue in AngularJS. While trying to showcase my problem through a jsfiddle, it turned out to be too reliant on multiple files and not yet accessible online. So please bear with the lengthiness of my explanation.
The situation is that I have developed an application using yeoman init angular
, and within my app.js
, the structure appears as below:
"use strict"
var myApp = angular.module("myApp", [])
.config(function($routeProvider) {
$routeProvider
.when("/lineup", {
templateUrl: "views/lineup.html",
controller: "LineupCtrl"
})
//other routes
.otherwise({
redirectTo: "/"
});
})
.directive("playerlist", function() {
return {
restrict: "E",
transclude: false,
scope : {},
templateUrl : "views/directives/playerlist.html",
controller : function($scope) {
$.get("/players")
.success(function(players) {
$scope.players = players;
});
},
replace : true
}
});
In my index.html
, I reference app.js
, and there's an anchor pointing to #/lineup
, which triggers the display of views/lineup.html
. For simplicity, let's assume that lineup.html
only contains the custom tag
<playerlist></playerlist>
.Within the directive's controller function, I can confirm that
$.get("/players")
functions correctly by inspecting Chrome's network tab for the expected array of players retrieved from the server.Additionally, the contents of
views/directives/playerlist.html
consist of the following code to format and display the player list:
<table class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Role</th>
<th>Strength</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="player in players">
<td>{{player.first_name}} {{player.last_name}}</td>
<td>{{player.age}}</td>
<td>{{player.role}}</td>
<td>{{player.strength}}</td>
</tr>
</tbody>
</table>
The intention behind creating the "playerlist" directive was to keep it independent from LineupCtrl
for potential reuse elsewhere in the project.
When clicking on the anchor to load #/lineup
for the first time, the tbody
element remains empty initially. Interestingly, upon clicking again, the table populates correctly with the player data fetched using $.get("/players")
. This delay in rendering could potentially be attributed to the time gap between loading playerlist.html and assigning values to the $scope.players variable. But isn't Angular designed to update views automatically when scope variables change?
Seeking assistance with resolving this issue!
Regards,
Andrea