I have question regarding AngularJS. I want to make ng-repeat for some array. But data for this array i get from firebase in controller.
Problem is, when page is rendering, iam still waiting for data from async function which get data from firebase.
What is the best way to control it?
I tried to used promisses, but something was wrong and page was rendered before i got data from firebase.
i.e
$scope.games = [];
function getOnce(){
var defer = $q.defer();
ref.once("value", function(data) {
defer.resolve();
$scope.games.push('test');
});
return defer.promise;
}
$scope.getdata = getOnce().then(function(data){
console.log('success');
console.log(data);
});
And i call '$scope.getdata' function on init 'data-ng-init="getdata()"'
What i wrong here? Or how can i get my goal?
Pass data in method resolve. In then populate the array with data response.
$scope.games = [];
function getOnce(){
var defer = $q.defer();
ref.once("value", function(data) {
defer.resolve('test');
});
return defer.promise;
}
$scope.getdata = getOnce().then(function(data){
$scope.games.push(data);
console.log('success');
console.log(data);
});
Well you could use an ng-show to just hide the parts of the page you don't want visible while you're loading the data. Or ng-if if your directives require that the data be loaded when their link/controller functions are ran by angular.
Does that suit your needs?
You'd need to expose whether or not you're done loading to the $scope with something like this:
$scope.isDoneLoading = false;
$scope.getdata = getOnce().then(function(data){
// ...
$scope.isDoneLoading = true;
});
Then you would just do this:
ng-if="isDoneLoading"
Or this, depending on your needs:
ng-show="isDoneLoading"
Related
I have an API call that's working great, but I'd like to use it on several controllers so I moved it to it's own service. I'm running into what looks like a classic Scope issue or a misunderstanding of Angular's digest cycle.
'use strict';
myApp.factory('Stuff',['$http', function ($http) {
var Stuff = {};
Stuff.data = {};
Stuff.api = 'http://localhost:8080/api/';
Stuff.getStuff = function() {
var http_stuff_config = {
method: 'GET',
url: Stuff.api + 'stuff/'
};
$http(http_stuff_config).then(function successCallback(response) {
Stuff.data = (response.data);
console.log(Stuff.data); // Returns populated object.
},function errorCallback(response) {
console.log(response.statusText);
});
};
Stuff.getStuff();
console.log(Stuff.data); // Returns empty object.
return Stuff;
}]);
myApp.controller('appController', ['$scope','Stuff',function($scope,Stuff) {
$scope.stuff = Stuff;
console.log($scope.stuff.data); // Returns empty object.
$scope.stuff.getJobs();
console.log($scope.stuff.data); // Returns empty object.
}]);
Here's the big clue. The essential output of above, in order is...
empty object (in service after calling method)
empty object (in controller before calling method)
empty object (in controller after calling method)
populated object (in method execution from service)
populated object (in method execution from controller)
So somewhere between the scope of the getStuff() method and Angular's order of operations, I'm doing something remarkably foolish. Thank you in advance.
You need to add returns on your service, or else the promise will not be returned to the controller. It is not good practice to just store the returns in your services AND NOT return the result to the controller.
This is considered bad practice because, any time you update the data on the service everyone will need to apply $scope.$watch to the service to look for updates. This can be very expensive in large scale apps.
The best Idea is to return the data to the calling controller (if you do not need to cache it, this we can talk about later) and let the controller access it via the promise service.getthing().then(function(result){});
myApp.factory('Stuff',['$http', function ($http) {
var Stuff = {};
Stuff.data = {};
Stuff.api = 'http://localhost:8080/api/';
Stuff.getStuff = function() {
var http_stuff_config = {
method: 'GET',
url: Stuff.api + 'stuff/'
};
return $http(http_stuff_config).then(function successCallback(response) {
return response.data;
console.log(Stuff.data); // Returns populated object.
},function errorCallback(response) {
console.log(response.statusText);
});
};
Stuff.getStuff();
console.log(Stuff.data); // Returns empty object.
return Stuff;
}]);
myApp.controller('appController', ['$scope','Stuff',function($scope,Stuff) {
$scope.stuff = Stuff;
console.log($scope.stuff.data); // Returns empty object.
$scope.stuff.getJobs().then(function(result) {$scope.stuff = result; console.log(result);});
console.log($scope.stuff.data); // Returns empty object.
}]);
I recommend you not to store the result inside the service itself (Stuff.data). Just return your data in the getStuff function and let the appController's scope store the data instead.
remember that $scope.stuff.getJobs() is async
(meaning you can't actually call console.log($scope.stuff.data) on the next line and get the data)
Now if you had a view, with something like <span ng-bind="stuff.data.property"> you could see it work just fine because the view will update by itself when the async function is done. (this is part of angular)
You need to understand that when you run $http, it is making an AJAX request. therefore it will not return an result immediately.
Therefore, if you attempt to use the data coming from $scope.stuff.getJobs(); immediate after invoking this function, you are likely to get nothing.
What you should do is to have your Stuff.getJobs() return a promise, and use promise.then(your own success handler) to correctly handle the returned response.
I have cleaned up your code a little bit. The following is a running sample of your code retrieving data from Yahoo Weather API.
You can play with it on CODEPEN.
html:
<div ng-app="myApp" ng-controller="appController">
<p>{{data}}</p>
</div>
JS:
var myApp = angular.module("myApp", []);
myApp.factory('Stuff',['$http', function ($http) {
var Stuff = {};
Stuff.data = {};
//sample yahoo weather api
Stuff.api = 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22nome%2C%20ak%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys';
Stuff.getData = function() {
var http_stuff_config = {
method: 'GET',
url: Stuff.api + 'stuff/'
};
return $http(http_stuff_config);
};
return Stuff;
}]);
myApp.controller('appController', ['$scope','Stuff',function($scope,Stuff) {
$scope.data = "$http service not ran";
var uncompletedAjaxCall = Stuff.getData();
uncompletedAjaxCall.then(
function(responseData){
$scope.data = responseData;
},
function(errorMsg){}
);
}]);
I'm new in angular and I need help to call an http request.
I had this controller
var app = angular.module('myApp',[]);
app.controller('freeUserController', function($scope, $http) {
$http({
method: 'GET',
url: 'users'
}).then(function successCallback(response) {
$scope.users = response.data.result;
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
});
It allows to fill Select in a modal form
This Select change every time user click on confirm button(select shows free users) so I though to create a service with the above http call and use this or on confirm button ( or on inside javascript of confirm button) or when user clicks on select tho show user.
So I change angular code like this:
var app = angular.module('"modalUploadLicense"',[]);
app.controller('freeUserController', function() {
freeUserService();
});
app.service("freeUserService",function($scope, $http){
$http({
method: 'GET',
url: 'users'
}).then(function successCallback(response) {
$scope.users = response.data.result;
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
});
But it give me an error and moreover I don't know the best way to call the service when the user list change.
This is my confirm button javascript:
$("#createLicenseButton").click(
function() {
var form = $("#addLicenseForm");
$.ajax({
type : "POST",
url : form.attr("action"),
data : form.serialize(),
// all right with rest call
success : function(data) {
//No exception occurred
if (data.status==true){
//Also the field are right(for e.g. form value)
if(data.success==true){
//il risultato sta in data.result
//window.location.reload(true);
$('#licensesTable').load(document.URL + ' #licensesTable');
angular.element(document.getElementById('freeUserController')).scope().get();
//reload only the tag with id carsTable, so only the table
//$('#carsTable').load(document.URL + ' #carsTable');
$('#addLicenseModal').modal("hide");
notifyMessage("Your license has been created!", 'success');
}
else{
//code if there are some error into form for example
}
} else {
//code exception
$('#addLicenseModal').modal("hide");
notifyMessage("Error! Your license hasn't been created!", 'error');
}
},
//error during rest call
error : function(data) {
window.location.href = "/ATS/500";
}
});
});
Whereas html Select is:
<label>Username</label> <select class="form-control select2"
style="width: 100%;" name="user" ng-model="selectedItem" ng-options="user.username as user.username for user in users track by user.username">
</select>
How can I update my Select value?thanks
First, change your service so it has a function to call:
app.service("freeUserService",['$http', function($http){
var service = this;
service.getusers = getusers;
function getusers() {
var url = "your url gets here";
return $http.get(url);
}
}]);
Then like Arnab says, you need to change your controller:
app.controller('freeUserController', ['freeUserService', '$scope', function(freeUserService, '$scope') {
$scope.fetchusers = function() {
freeUserService.getusers()
.then(handleGetUsers)
.catch(handleErrors);
}
function handleGetUsers(result){
//This is a promise, because $http only does asynchronous calls. No
//need to wrap this in a jquery thingy.
//As soon as the async function is resolved, the result data is put
// on your scope. I used $scope.users on purpose, because of your
//html
$scope.users = result.data;
}
function handleErrors(error){
console.log(error);
}
}]);
As you can see, I have put the "variable" users on the scope. I did this on purpose because of your html
<label>Username</label> <select class="form-control select2"
style="width: 100%;" name="user" ng-model="selectedItem" ng-options="user.username as user.username for user in users track by user.username">
</select>
The select looks into the scope for a variable called users. Because the variable users is on your html, angular automatically watches the variable for changes.
What I understand from your question is that every time the http call is done, you get another result, right? So Angular will automatically watch for a change, and reflect the result on your select element. if interested in more information, you should read this. I also suggest following a 'start with Angular tutorial', because going from your question, I think you are missing the basics of Angular.
The last step you need to do (I think, if i understand your question), is bind the $http function to your HTML. There is a "ng-click" directive you can use. In your case, the button then could look like this:
<button ng-click="fetchusers()" type="submit">Get me new users</button>
As you can see, I use the $scope.fetchusers() function in the ng-click directive, wich will make a new http call, getting new uses (ofcourse, if the http call gets new users every time you call it).
Plunker with modified code here.
You can use the ng-init directive to initialize the value. I ll update my plunker so that you can see how the ng-init works. You should set it right next to your ng-controller. ng-init will make the first call and give you data from the start. Then every time you press the button, new data will come, and your select will be updated. I have updated the plunk. I have added one of my own webservices. Do mind, my webservices are on a free heroku account. If you wait too long, the heroku application will go to sleep mode and the first call for data will timeout.
About multiple asynchronous calls:
Angular promises can be chained! So you can do one asynchronous call (for example doing a post to a database), wait for it to finish, then get the updated data. In your service, you could do this:
function getUsers(parameters) {
var posturl = "url to post to";
return $http.post(url, data) //the update, it returns a promise
.then(handlePost)
.catch(handleError);
}
function handlePost(result){
//the $http.get will only be executed after the previous promise has been
//resolved!
var geturl = "url to get data from";
return $http.get(url); // this is the second asynchronous call
}
It is good practice to chain promises. It would be bad practice to use a jQuery ajax call for this.
Inject freeUserService to your controller freeUserController to atleast call the service from your controller, like:
app.controller('freeUserController', ['freeUserService', function(freeUserService) {
freeUserService();
}]);
Otherwise you write like this:
var app = angular.module('myApp',[]);
app.controller('freeUserController', ['freeUserService', function($scope, freeUserService) {
var promise = freeUserService();
promise.then(function successCallback(response) {
$scope.users = response.data.result;
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
// And bind the users variable in your template
}]);
app.service("freeUserService", ['$http', function($http){
return $http({
method: 'GET',
url: 'users' // Proper url to your api
});
}]);
I have an factory that gets data from my backend:
as.factory("abbdata", function GetAbbData($http,$rootScope,$routeParams,$q) { //$q = promise
var deffered = $q.defer();
var data = [];
var abbdata = {};
abbdata.async = function () {
$http.get($rootScope.appUrl + '/nao/summary/' + $routeParams['id']).success(function(d) {
data = d.abbData;
deffered.resolve();
});
return deffered.promise;
};
abbdata.data = function() {
return data;
};
return abbdata;
});
A call my factory like this in my controller:
abbdata.async().then(function() {
$scope.abbData = abbdata.data(); //Contains data
});
When I do a console.log($scope.abbData) outside my service call, just underneath, the result Is undifined. Why? Should not the $scope.abbData contain the data from my service after I call it?
EDIT:
You need to pass the data that should be returned into the resolve function like this:
deffered.resolve(data);
EDIT:
To get the data in the controller do this:
abbdata.async().then(function(data) {
$scope.abbData = data; //Contains data
});
Why don't you simply return that value from the async call in the first place?
You can chain promises so by attaching a success handler in your factory and returning a value from that you can simplify your code to:
as.factory("abbdata", function GetAbbData($http,$rootScope,$routeParams) {
return {
async: function () {
return $http.get($rootScope.appUrl + '/nao/summary/' + $routeParams['id']).success(function(d) {
return d.data.abbData;
});
}
}
});
And then use it like
abbdata.async().then(function(data) {
$scope.abbData = data; //Contains data
});
if you console.log($scope.abbData) outside the service call it should show undefined, since the call is asynchronous.
abbdata.async().then(function() {
$scope.abbData = abbdata.data(); //Contains data
});
console.log($scope.abbData) // this should show undefined
The console.log($scope.abbData) just after setting the abbData should show the data
abbdata.async().then(function() {
$scope.abbData = abbdata.data(); //Contains data
console.log($scope.abbData) // this should show the data
});
EDIT
you can use abbData from your service call like for example
angular.module('myApp', []).controller('HomeCtrl', function($scope, abbdata){
var updateUI;
$scope.abbData = [];
abbdata.async().then(function() {
$scope.abbData = abbdata.data(); //Contains data
updateUI();
});
updateUI = function(){
//do something with $scope.abbData
}
});
EDIT 2
On response to your query, I would do something like,
angular.module('myApp', [])
.controller('JobsCtrl', function($scope, $jobService) {
$scope.jobs = [];
$jobService.all().then(function(jobs) {
$scope.jobs = jobs;
});
})
.service('$jobService', function ($q, $http) {
return {
all: function () {
var deferred = $q.defer();
$http({
url: 'http://url',
method: "GET"
}).success(function (data) {
deferred.resolve(data);
}).error(function () {
deferred.reject("connection issue");
});
return deferred.promise;
}
}
});
associated view
<body ng-app = "myApp">
<div ng-controller = "JobsCtrl">
<div ng-repeat="job in jobs track by job.id">
<a href="#/tab/jobs/{{job.id}}" class="item item-icon-right">
<h2>{{job.job_name}}</h2>
<p>DUE DATE: {{job.job_due_date}}</p>
</a>
</div>
<div>
</body>
Here the service an all function which returns a promise, i.e. it will notify when data is fetched.
in the controller the service is called and as soon the service call is resolved the $scope.jobs is assigned by the resolved data.
the $scope.jobs is used in the angular view. as soon as the jobs data are resolved, i.e. $scope.jobs is assigned, the view is updated.
hope this helps
I had a quick look, I have 2 ideas:
First theory: your service is returning undefined.
Second theory: you need to run $scope.$apply();
See this fiddler: https://jsfiddle.net/Lgfxtfm2/1/
'use strict';
var GetAbbData = function($q) {
//$q = promise
var deffered = $q.defer();
var data = [];
var abbdata = {};
abbdata.async = function () {
setTimeout(function() {
//1: set dummy data
//data = [200, 201];
//2: do nothing
//
//3: set data as undefined
//data = undefined;
deffered.resolve();
}, 100);
return deffered.promise;
};
abbdata.data = function() {
return data;
};
return abbdata;
};
var abbdata = GetAbbData(Q)
abbdata.async().then(function() {
console.log(abbdata.data()); //Contains data
});
I have stripped away a lot of dependencies and replaced $q with Q just for my own ease.
In the above example, I first attempted to run the code with dummy data, the console output the expected data, then I tried to not assign the data, and I get an empty array. This is why I assume that if you are seeing 'undefined' you must be explicitly setting the value to 'undefined'.
That aside, I also noticed that you were testing the result by reading directly from $scope. I know that when not inside the angular scope, doing operations on the $scope object does not necessarily happen in a timely manner, and typing $scope.$apply() usually fixes this. Usually, when using $http, angular keeps you in the appropriate scope, but you are creating your own promise using $q so this could be another potential issue.
Finally, the other two answers have pointed out that you are not using promises in the standard way. Although your code works fine, it is not normal to set your data directly onto your service and retrieve it from there. You can keep your service stateless by simply resolving your promise with the data that you want to process in the then method as shown by the answers by Anzeo and Markus.
I hope I was able to find the solution, good luck.
Dipun
as.factory("abbdata", function GetAbbData($http,$rootScope,$routeParams,$q) { //$q = promise
var deffered = $q.defer();
var data = [];
var abbdata = {};
abbdata.async = function () {
$http.get($rootScope.appUrl + '/nao/summary/' + $routeParams['id']).success(function(d) {
data = d.abbData;
deffered.resolve(data);
});
return deffered.promise;
};
abbdata.data = function() {
return data;
};
return abbdata;
});
I'm trying to create a simple form with Angular, and need to render server-side validation errors. Our REST API handles validation errors with a 422 status code and a JSON array of errors in the response body.
My Controller:
.controller('MyController, function($scope, $http) {
$scope.save = function() {
var promise = $http.post('http://myapi.net/resources', $scope.data)
.success(function(data) {
// Success
})
.error(function(data, status) {
$scope.errors = data.errors;
});
$scope.errors = [];
return promise;
};
});
My Template:
<span ng-repeat="e in errors" class="error">
{{e.field}} - {{e.message}}
</span>
The errors render correctly after the first POST, but if a second POST fails, the errors sent by the server are appended in the DOM. The previous batch of errors remains, making it appear that no improvements to the data have been made. Stepping through the code, the $scope variable has the correct data, but the DOM does not. Is there a way to force ng-repeat to destroy all its previous DOM and build new ones? Or is there a better way to debug this so I can see what is going on?
As #tymeJV said it should just work. How about resetting the errors array using an empty array:
myApp.controller('MyController', function($scope, $http) {
$scope.save = function() {
// always a good idea
$scope.errors = [];
// ...
});
Here's also a plunk, maybe you can recreate it there.
Well I don't know what's going on with ng-repeat, but after 2 days I've discovered a workaround. Using a second scope variable and a watch seems to restore the correct behavior:
.controller('MyController, function($scope, $http) {
$scope._errors = [];
$scope.$watch('_errors', function(val) {
$scope.errors = val;
});
$scope.save = function() {
var promise = $http.post('http://myapi.net/resources', $scope.data)
.success(function(data) {
// Success
})
.error(function(data, status) {
$scope._errors = data.errors;
});
$scope.errors = [];
return promise;
};
});
Why this isn't necessary in the success callback is beyond me, but there you go.
I have two ajax calls in a service; the first one, AjaxOne gets the data I want from fields (user entered), I then want to alter the data by passing it to another ajax call, AjaxTwo to get the results I need. Both ajax calls are completely different services and can be interacted with by multiple controllers so I've placed then in their own unique Angular factory methods (could be service).
Issue is I'm thinking traditional sequential code running akin to PHP in my little semi-sudo code below (which I know will not work but just for example of how I would solve it in PHP), but I know I need to be thinking in parallel but can't quite get my head around what I need to do for the controller to be able to pass the results from AjaxOne to AjaxTwo. Keep in mind that both factory methods don't need to know of each other existence (to create no coupling and make then highly reusable).
How would I go about doing what I need to with Angular?
app.controller('app', function( $http, $scope, AjaxOne, AjaxTwo ) {
$scope.fields = '';
$scope.ajaxOne = AjaxOne;
$scope.ajaxTwo = AjaxTwo;
$scope.results = [];
$scope.process = function () {
AjaxOne.getResults($scope.fields);
$scope.results = AjaxTwo.getResults(AjaxOne.results);
};
});
Thanks.
Seems like you need to adjust your AjaxOne service to accept a callback, which would asynchronously call AjaxTwo only when AjaxOne is done doing whatever it does:
// Inside AjaxOne:
$scope.getResults = function(things, cb) {
// do something with `things`. Let's assume you're using $http:
$http({
url: "http://example.appspot.com/rest/app",
method: "POST",
data: {
"foo": "bar"
}
}).success(function(data, status, headers, config) {
cb(data);
});
};
// In your original example:
app.controller('app', function($http, $scope, AjaxOne, AjaxTwo) {
$scope.fields = '';
$scope.ajaxOne = AjaxOne;
$scope.ajaxTwo = AjaxTwo;
$scope.results = [];
$scope.process = function() {
AjaxOne.getResults($scope.fields, function(resultsFromAjaxOne) {
$scope.results = AjaxTwo.getResults(resultsFromAjaxOne);
});
};
});
You should use the promises that you get with the $http service it will give something like this
app.controller('app', function( $http, $scope, AjaxOne, AjaxTwo ) {
$scope.fields = '';
$scope.results = [];
$scope.process = function () {
AjaxOne.getResults($scope.fields).success(function(results){
AjaxTwo.getResults(results).success(function(results2){
$scope.results = results2;
});
});
};
});
for more information you can check this url http://docs.angularjs.org/api/ng/service/$http