Exploring the world of AngularJS, I embarked on a mission to create a file upload feature along with other form data. While there are numerous scripts and plugins available, I decided to utilize my own custom service using $xhr. Despite successfully sending the file, I encountered an error, bug (not an actual error or bug, just used as placeholders) which made me question my understanding of AngularJS. Here's a snippet of my code:
.
JS
var app = angular.module('ngnNews', []);
app.factory('posts', [function () {...}]); // Trimmed for brevity
app.factory('$xhr', function () {
var $xhr = { reqit: function (components) { ... //My Xml HTTP Request codes here }}
return $xhr;
});
app.controller('MainCtrl', ['$http','$scope','$xhr','posts',
function ($http, $scope, $xhr, posts) {
$scope.posts = posts.posts;
$scope.files = [];
var newPost = { title: 'post one', upvotes: 20, downvotes: 5 };
$scope.posts.push(newPost);
$scope.addPost = function () {
$xhr.reqit({
form: document.getElementById('postForm'),
callbacks: {
success: function (result) {
if (result.success) {
console.log($scope.posts); //[FIRST OUT]
$scope.posts.push(result.post);
$scope.title = '';
console.log($scope.posts); //[SECOND OUT]
}
}
},
values: { upvotes: 0, downvotes: 0 },
files: $scope.files
});
...
}
}]);
.
HTML
<form action="/Home/FileUp" id="postForm" method="post" enctype="multipart/form-data">
<div class="form-group input-group">
<span class="input-group-addon">Post Title</span>
<input name="title" class="form-control" type="text" data-ng-model="title" />
</div>
<ul>
<li ng-repeat="file in files">{{file.name}}</li>
</ul>
<button class="btn btn-primary" type="button" data-ng-click="addPost()">Add New</button>
</form>
SCREEN
A sample post displayed in the list
.
PROBLEMS
Upon clicking the Add New button for the first time, everything seems to work smoothly until
$scope.posts.push(result.post);
. The console displays [SECOND OUT]:
The first object has a $$hashKey, but the second object sent from the server (added by the$scope.posts.push(result.post);
function) does not have it. This inconsistency leaves me questioning why this is happening. Moreover, upon clicking the Add New button for the second time, everything completes successfully without any new logs appearing in the console, and the newly added post is shown on the list as depicted in the screen image above.
MAIN PROBLEM
Although I pushed the returned value from the server, the post list (on the screen) remains unaffected after the first click.
QUESTIONS
- What exactly is causing this behavior? or
- Where am I going wrong? Any insights would be greatly appreciated.