Angular data is not binding in $http.post success method - angularjs

I found one weird issue while working in angular js
I am getting data using ajax call. I am binding data to $scope object but view is not getting updated after data bind
following is my code
$scope.getPlanDetail = function (){
$rootScope.planBody.checkUpdate= false;
$http.post('http://MyServerURL',JSON.stringify($rootScope.planBody)).
success(function(response){
$scope.dataVal = response;//Able to view data in console;
console.log($scope.dataVal)//data json shown in log window
localStorage.setItem("tempDataVal", JSON.stringify(response));//able to set data in localStorage;
}
}
getPlanDetail() function is getting called on btn click using ng-click
Same functionality I have done in other case(using get method.) where code is working properly. The only diff I found is that current AJAX call is taking to much of time because of too much of server side processing and its post method I am not sure whether this(using post method) is causing issue in binding
On same view(.html) I added dummy button ng-click event. After ajax success call I click on button and view is loaded because of data use from localStorage variable.
$scope.dummyClick= function(){
console.log($scope.dataVal);//giving Undefined
$scope.dataVal = JSON.parse(localStorage.getItem("tempDataVal"));// this time view binded properly.
}
I didn't understand why data is not bind to view in success method. Does the $scope time out after some time if server takes too much time to respond?
Thanks in Advance.

If you are changing the model inside an ajax call then you need to notify the angular js that you have some changes.
$scope.$apply(); after the below line will fix your issue. This line will update the scope.
$scope.dataVal = response;
Thanks,
Santyy

Related

Angular js UI grid is not getting updated with new content

I am calling $http.get to get new content from the server for angular ui grid. On change of date in the datepicker I trigger an ng-change event to make another http call to get new content. The call is successful but the grid is not updated with new content.$scope.grid.core.notifyDataChange() throws error when called inside the http success call back.Please suggest ways to update the grid with new content.
Please find the plnkr code. when I click load button, I want to update grid with new JSON data using http call but it is not updating grid. http://plnkr.co/edit/S2A3scEoO6QIGFbru3Lr?p=preview
The problem with your example is inside $http's success method(lines 256-260).
$http.get(...).success(
function(data){
$scope.roData = data;
});
There you are just putting your data inside a scope property ($scope.roData), but then you're not doing anything with that scope property.
Furthermore you're trying to assign a wrong value to uiGrid.gridOptions.data with the lines:
if($scope.gridOptions.data ==='rData'){
$scope.gridOptions.data = 'roData';
}
But you did 2 mistakes:
Treating variables as string, and this is not going to work. Inside your JS files you need to access your scope with $scope.nameOfVariable not by using their names as strings like 'nameOfVariable'.
You put these lines outside of your success method, so they are executed before you actually get your data.
I managed to edit your plunker and make it work, you can find it here.
What I did was putting your lines together and fix the name error. I did not put there any if since I don't know what logic you wanted to accomplish.
$http.get(...).success(
function(data){
$scope.roData = data;
$scope.gridOptions.data = $scope.roData;
});

Angularjs view not reflecting the data retrieved from pouchDB (in browser database)

Background:
I am building my offline application which uses AngularJS for UI and PocuhDB for locally storing the data retrieved from the server.
Issue:
The data retrieved from PouchDB is not getting rendered in the UI.
Controller:
$scope.retrieveView = function (sys, code, majorVer, minorVer) {
var promise;
promise = dataService.getDataFromLocalDb().then(
function(dataFromPouchDb){
$scope.data = dataFromPouchDb.data;
});
return promise;
}
And then in the UI code I have the following :
<h1> {{data}}</h1>
I have debugged the code and everything seem to work fine. But the data is not getting displayed in the UI.
If I hard code a value to the data field then its getting rendered in the UI
$scope.data ="TEST";
This question is kind a old but I just came around it.
Issue is that Angularjs is based on so called digest cycles. When your model or view is changed digest cycle is triggered, watch for changes and update model or view respectively. It is so called two way data binding.
This digest cycle is not triggered periodically on some time base but on events instead. Those events are angular directives like ng-click, ajax calls $http or some other angular events like $timeout. You can find more information about digest here.
In general you should use those things when working with angular application to avoid such situations. In some cases its not possible however like in your case when getting data from DB. Digest cycle is not triggered and your view is not updated by angular.
Workaround for this is manually trigger $digest cycle. Way you have described:
if(!$scope.$$phase) {
$scope.$digest();
}
is working but considered as angular anti-patern and is discouraged by angular team, you should use:
$timeout();
instead. For more information see this answer.
I would maybe consider adding $timeout() call to hook for insert, update, delete hooks or events. Maybe pouchDB sync could be helpfull there.
The code you show seemed correct, maybe you can use console.log() to track the progress of the data. I think the problem might not in this layer. Maybe in the area where you wrapped getDataFromLocalDb(), track and find if the data have transfer to here, or where it disappeared.
The code started to work when i added the following :
if(!$scope.$$phase) {
$scope.$digest();
}
But i have no idea what magic does this code do.
It would be a great help if some some could advice.
The complete code that works now is :
$scope.retrieveView = function (sys, code, majorVer, minorVer) {
var promise;
promise = dataService.getDataFromLocalDb().then(
function(dataFromPouchDb){
$scope.data = dataFromPouchDb.data;
if(!$scope.$$phase) {
$scope.$digest();
}
});
return promise;
}

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!

How come Angular doesn't update with scope here?

I'm pretty new to Angular and I'm using firebase as my backend. I was hoping someone could debug this issue. When I first go to my page www.mywebsite.com/#defaultHash the data doesn't load into the DOM, it does after visiting another hash link and coming back though.
My controller is like this:
/* initialize data */
var fb = new Firebase('https://asdf.firebaseio.com/');
/* set data to automatically update on change */
fb.on('value', function(snapshot) {
var data = snapshot.val();
$scope.propertyConfiguration = data.products;
console.log($scope.propertyConfiguration);
console.log("Data retrieved");
});
/* save data on button submit */
$scope.saveConfigs = function(){
var setFBref = new Firebase('https://asdf.firebaseio.com/products');
setFBref.update($scope.propertyConfiguration);
console.log("configurations saved!");
};
I have 3 hash routes say "Shared", "Registration", and "Home" with otherwise.redirectTo set to "Shared".(They all use this controller) Here's the error that occurs: (all "links" are href="#hashWhereever")
1) Go to website.com/#Shared or just refresh. Console logs $scope.propertyConfiguration and "Data Retrieved". DOM shows nothing.
2) Click to website.com/#Registration, console logs $scope data properly, DOM is loaded correctly.
3) Click back to website.com/#Shared, console logs $scope data properly yet this time DOM loads correctly.
4) Refresh currently correctly loaded website.com/#Shared. DOM elements disappear.
Since $scope.data is correct in all the cases here, shouldn't Angular make sure the DOM reflects the model properly? Why is it that the DOM loads correctly only when I am clicking to the page from another link.
I can "fix" it by adding window.location.hash = "Shared" but it throws a huge amount of errors in the console.
FIXED:(sorta)
The function $scope.$apply() forces the view to sync with the model. I'd answer this question myself and close it but I'm still wondering why the view doesn't load correctly when I correctly assign a value to $scope. If Angular's "dirty checking" checks whenever there is a possibility the model has changed, doesn't assigning a value to $scope overqualify?
Angular has no way to know you've assigned a value to $scope.variable. There's no magic here. When you run a directive (ng-click/ng-submit) or Angular internal functions, they all call $apply() and trigger a digest (a check of the dirty flags and update routine).
A possibly safer approach than $apply would be to use $timeout. Currently, if you call a write op in Firebase, it could synchronously trigger an event listener (child_added, child_changed, value, etc). This could cause you to call $apply while still within a $apply scope. If you do this, an Error is thrown. $timeout bypasses this.
See this SO Question for a bit more on the topic of digest and $timeout.
This doc in the Angular Developer Guide covers how compile works; very great background read for any serious Angular dev.
Also, you can save yourself a good deal of energy by using the official Firebase bindings for Angular, which already take all of these implementation details into account.
Vaguely Related Note: In the not-too-distant future, Angular will be able to take advantage of Object.observe magic to handle these updates.

Promises, make available on watch, angular JS

I have a problem with understanding promises.
$scope.$watch('selectedPipe', function() {
$scope.sizesFromPipes = test.getSizes($scope.selectedPipe.pipe_id);
$scope.sizesFromPipes.then(function(sizes){
$scope.selectedSize = sizes[0]; //Working
$scope.calculationResults = CalculationFactory.mainCalculation(sizes);
console.log($scope.calculationResults) //Working
});
console.log($scope.calculationResults) //Is not getting updated, binded view is not getting updated either.
});
I have a view that listens on calculationResults. It works once when the app is loaded. But it's not getting updated outside when the watch triggers. How do I make calculationResults update "outside" so my view can access it?
A promise runs asyncronously, so your console output will fire before the promise actually finishes.
Here is a quick example showing the timing of a promise and properties being set on the $scope.
http://jsfiddle.net/jwcarroll/NNgw6/
Update:
I've created another example to try and show promises resolving at different times and how that shows up in the bindings.

Resources