ionic/angular refresh like count with interval? - angularjs

HI I'm building out a basic social media site with ionic and am tracking the like counts for each post. On page load I successfully show the like count that is in the db for each record.
$scope.getNewData = function () {
$scope.page = 1;
// get generic feed
FeedService.getFeed(1)
.then(function (data) {
//We will update this value in every request because new posts can be created
// console.log(data.totalPages)
$scope.totalPages = data.totalPages;
$scope.cards = data.posts;
$scope.$broadcast('scroll.infiniteScrollComplete');
return "loaded new data";
})
.then(function (data) {
//$rootScope.$broadcast('newDataLoaded');
})
$scope.$broadcast('scroll.refreshComplete');
};
Issue is after the page loads and another user likes the record I want the like count to automatically update for all users. I started playing around with $interval which works but the whole $scope changes , almost looks like a page refresh. How can I only update the $scope.cards.Post_Likes_Count without having to refresh the entire $scope.cards?
Here is my markup:
<div class="actions-brief">
{{card.Post_Likes_Count}} Likes
<a ng-controller="CommentsCtrl" ng-click="showComments(card)" class="subdued">{{card.comments}} Comments</a>
<!--{{card.shares}} Shares-->
</div>
Ideally I would just want to refresh the $scope.cards.Post_Likes_Count. Not sure how to keep everything in sync if I don't use $scope.cards. I show 10 posts per page but as the user scrolls I grab 10 more records.
Any suggestions or tips would be greatly appreciated.

The whole $scope should not change ... According to best practices, you should make the $http call in factory or service. Lets say you made an http call to your server to update the like done by your one user... You should call activate() function..
Activate function should be a user defined function which makes a request to the server while loading the page to get all the data from database and reload the $scope.yourData variable with latest data.
Moreover you should call the same activate() function from your controller using $interval. This would make your code more structured and proper.
And moreover you should push data in your $scope.YOURDATA variable in your activate() function rather than assigning it each time...

Related

AngularJS reloading multiple tab in the same time if any change

I have an add form that if the user file the form and submit, in the same time, user can see the data in the same page in table with ui-view and this is not an issue!!
Problem is: if i open more than one tab in the same browser, that post or change reflection doesn't show in other tab without refreshing or reloading. i want to see change in other tab of browser or other browser without reload
I want to see the change without refresh or reloading.
if i reload in other tab, it works but if i dont reload in other tab, the change doesn't effect
here you go for my post method:
$scope.formModel = {};
$scope.onSubmit = function () {
$http.post('http://127.0.0.1:8000/api/v1/contact/create/', $scope.formModel)
.then(function(response) { //if success, below fuction will execute
$scope.successPost = 'You have successfully submitted your Contact';
$timeout(function() {
$scope.successPost = '';
}, 4000);
//below $scope will push data in client site if the request is success
$scope.contacts.push(response.data);
//if any error occurs, below function will execute
}, function(response) {
// below variable will get predefined message that will explain exactly what happened
var errorData = response.data;
$scope.errorPost = Object.values(errorData)[0][0];
$timeout(function(){
$scope.errorPost = '';
}, 4000);
});
$scope.formModel = {}; //It means, after submit, the form field will clear
$scope.addContactForm.$setPristine();
};
I want to see the change in the other tab without refresh or reload
well browser tabs are per definition separated from each other and can't communicate directly between each other.
there are certain possibilities to handle that: for example you can have a separate external service and always poll that service for latest changes and if something changes automatically call reload.
or you could use a service that provide a websocket that sends you to the frontend an update notification once something changed in your data.
Just want to point you in the right direction, the topic is to big to provide a finished solution. I recommend to do some research on how to communicate between tabs / how to build a service with an update notification for new data
Edit: Just to add #Yftach point from the comments: Theoretically localstorage is shared between tabs, so theoretically you could have a variable there and watch in an interval for changes. However the solution with a separate server is (at least in my eyes) way better

using angularjs to refresh view's data automatically when the data in database is changed

is it possible to use angularJs to refresh view's data automatically when the data in database is changed? Please help me how to do it
I made this script, but as you can see the data only refresh if viewData() is triggered.
$scope.viewData = function(){
$http.get("sample.php").then(function(response){
$scope.mine = response.data;
});
}
I want to create page like timeline in twitter which can load new tweets without refreshing the page. Thank you
You can do longpolling like this from Angular side:
setInterval($scope.vievData, 1000);
since setInterval is not monitored by Angular you will have to add the following line in $scope.viewData
$scope.$$phase || $scope.$digest();
immediately after $scope.mine=...
This will refresh $scope.mine every second regardless of the changes in DB, it is a bit crude. To do this only when the values are changed in the database you will probably have to use WebSockets, but that is a bit more complex, both front and back.

How to use $resource in AngularJS properly for building a client app?

I've been following this tutorial http://draptik.github.io/blog/2013/07/28/restful-crud-with-angularjs/. I implemented a Grails backend with it instead of the Java one in the tutorial.
I've got the data coming back and forth, with one issue. If I create/update/delete a user, I don't see the changes reflected on my user list when I am redirected back. I have to refresh the page to see the updates.
Looking at the network traffic for an edit, it looks like it does a PUT and fires off the GET before the PUT is complete. Assuming this is because $resource returns a promise so things can be done asynchronously. So how do I handle this so that when $location redirects me, my list is up to date?
I'm guessing the options are to wait for the PUT to complete before redirecting/querying for the list, or to somehow manually manage the $scope.users to match the request?
Or maybe this tutorial is just a bad example? Maybe there is a better way to do it (still using $resource)?
Note: I've seen Restangular out there, and I've seen $http with success callbacks, but I would like to understand the situation above.
One way to overcome this issue would be to not redirect to the list page, till you get a callback, and then do a redirect. You can show some busy indicator till that time. The resource call looks like this.
resource.update(config,data,function() { //gets called on success},
function(error) { //gets called on failure});
In real life scenario waiting for the response of update makes sense as you want to handle the error and success scenarios on the same page.
I don't see your code anywhere so i'm just assuming (based on what you wrote and your current problem)
You are probably doing a full (or partial) get each time you changed a user and (re)binding the result to your scope. Doing this in the callback of the resource should actually start the digest cycle angular does to update modified objects. If you had been doing the fetching outside $resource - for example with custom/jquery ajax you would need to execute $scope.$apply()
What i really don't understand you would need to wait for the callback. You already know you added/modified a user. Instead of 'detaching' that user from your scope, modify it, post it to your rest server, then wait for callback, and reinserting it into the scope - why not modify it directly in the list/array you put on your scope?
var users = Users.get(function () {
$scope.users = users.record; // bind the resulting records to the scope
});
$scope.updateUser = function (user) {
resource.update(...); //pseudo
};
Then in your html, you will keep a reference to the currentUser and the div-list will update automaticly.
<div ng-repeat="user in users" ng-click="currentUser=user">{{user.Name}}</div>
<input ng-model="currentUser.Name">
<button ng-click="updateUser(currentUser);">Update</button>
If you don't want to see the update in the list while you type, but only once your callback fires or when you hit the button, would would instead use another ng-model for your input like this:
<input ng-model="tempUser.Name">
And you would then copy the value other in either the updateUser method or in the resource callback like this:
$scope.updateUser = function (user) {
user.Name = $scope.tempUser.Name; // should update automaticly
resource.update(...) // pseudo
}
Hope it helped!

Cannot correctly refresh page using AngularJS

I have a page, which allows the user to add/edit/delete database table.
The database staff, and add/edit/delete, all work fine.
However, in my AngularJS method, I add location.reload(), trying to refresh the page to show the updated table. Unfortunately, the database has been updated, but the page isn't.
If I press F5 to manually reload, the result is right. I don't use route in the page.
Just want a simple function, and it can automatically refresh after being updated.
Below is sample codes
$scope.add = function(){
//add something in database
//no problem of this part
location.reload() //doesn't work
};
Try adding the $ and the location service to the controller
MyController($scope, $location){
$scope.add = function(){
$location.reload();
}
}

AngularJS calls $http constantly

Im very new to AngularJS (4 hours new) and I'm trying to get an http call working, however what it seems like its happening is Angular keeps calling the http get request over and over again. I'm sure this is because my approach is wrong. This is what I'm trying to do.
snippet of my controller file The webservice works fine. I am running this in a node.js app
function peopleController($scope,$http){
$scope.getPeople = function(){
$scope.revar = {};
$http.get('/location/-79.18925/43.77596').
success(function(data){
console.log(data);
$scope.revar = data;
});
}
}
My list.html file
<div ng-controller="busController">
<div class="blueitem">{{getPeople()}}</div>
</div>
I know I will not see the results since im not returing anything in my getPeople Method but I wanted to see the log output of the result which I did see in chrome, but a million times and counting since angular keeps calling that url method over and over again. Instead it keeps hitting.
How do I get angular to return the response just once?
The problem you are experiencing is linked to the way AngularJS works and - to be more precise - how it decides that a template needs refreshing. Basically AngularJS will refresh a template based on a dirty-checking of a model. Don't want to go into too much details here as there is an excellent post explaining it (How does data binding work in AngularJS?) but in short it will keep changing for model changes till it stabilizes (no more changes in the model can be observed). In your case the model never stabilizes since you are getting new objects with each call to the getPeople() method.
The proper way of approaching this would be (on of the possible solutions):
function peopleController($scope,$http){
$http.get('/location/-79.18925/43.77596').
success(function(data){
$scope.people = data;
});
}
and then, in your template:
<div ng-controller="busController">
<div class="blueitem">{{people}}</div>
</div>
The mentioned template will get automatically refreshed upon data arrival.
Once again, this is just one possible solution so I would suggest following AngularJS tutorial to get better feeling of what is possible: http://docs.angularjs.org/tutorial/
Couple of things. Welcome to angularjs, its a great framework. You probably shouldn't be calling getPeople from the webpage. Instead,
function peopleController($scope,$http){
var getPeople = function(){
$scope.revar = {};
$http.get('/location/-79.18925/43.77596').
success(function(data){
console.log(data);
$scope.revar = data;
});
}
getPeople();
}
and then in html
<div ng-controller="busController">
<div class="blueitem">{{revar|json}}</div>
</div>
Also, I would recommend you looking into the ngResource, especially if you are doing CRUD type applications.
Hope this helps
--dan

Resources