I am currently developing a test web application. The primary functionalities at the moment are user login and posting messages.
When the user clicks a button, the following code is triggered:
$scope.getData = function(){
$http.get('/messages').
then(function(response) {
if(angular.toJson(response.data.messages) != angular.toJson($scope.messages)) {
$scope.messages = response.data.messages;
$scope.clearAllSelected();
$scope.confirmRestOperation(response);
}
}, function(response) {
$scope.messages = [];
$scope.confirmRestOperation(response);
});
};
The HTML template associated with my model looks like this:
<div id="messages">
<md-card ng-repeat="message in messages" class="padding-medium box-sizing" ng-init="setAuthorDataFromAuthorId(message.author)">
<md-checkbox class="md-primary" ng-click="toggle(message.id, selected)" ng-model="exists(message.id, selected)"></md-checkbox>
<h4><b>Author: {{authorData[message.author].name}} ({{authorData[message.author].username}})</b></h4>
<img style="width:50px;height:50px;" ng-src="{{authorData[message.author].profile_picture}}" alt="(Picture)">
<p>Message: {{message.message}}</p>
<p>{{message.time | timestampToDate}}</p>
</md-card>
</div>
The objective here is to have each message contain an 'author' field which holds the author's ID. Upon initializing each card, I invoke a $scope
function called setAuthorDataFromAuthorId
, which takes an integer value - the ID of the message author. The function is as follows:
$scope.setAuthorDataFromAuthorId = function(id) { // line 22
console.log($scope.authorData); // line 23
if(id in $scope.authorData) return;
console.log("setAuthorFromAuthorId has been called");
$http.get('/getUserDataFromId/'+id).then(function(response) {
console.log(response.data); // line 27
console.log($scope.authorData); // line 28
$scope.authorData[id] = response.data;
}, function(response) {
console.log(response.data);
console.log($scope.authorData);
$scope.authorData = {};
});
console.log("setAuthorFromAuthorId has been completed");
};
The issue arises when multiple messages from the same author are displayed on the screen. Despite attempting to prevent redundant API calls by checking if the author's data is already present in $scope.authorData
, the output displays inconsistent behavior.
After switching the initialization method from ng-init
to ng-click
, the functionality improved significantly. However, I am still puzzled about why the original approach failed to work seamlessly with ng-init
.
Any suggestions on resolving this issue or insights into why ng-init
may not be functioning as expected would be greatly appreciated.
Thank you!