I am trying a quick test to debug why some of my code isn't working as expected.
I have a controller named testCtrl and a service myService . In the service, I am trying to get data from Parse and once I have the data, I am trying to load this data into my frontend html.
Here's the code:
app.controller('testCtrl', function($scope,myService) {
var currentUser = Parse.User.current();
$scope.username = currentUser.getUsername();
$scope.test = "ths";
var promise1 = myService.getEvaluatorData();
promise1.then(function(response){
$scope.results2 = response;
console.log(response);
});
});
app.factory('myService', function(){
return {
getAllData: function($scope){
getEvaluatorData($scope);
},
getEvaluatorData: function(){
var evaluators = Parse.Object.extend("Evaluators");
query = new Parse.Query(evaluators);
return query.find({
success: function(results){
angular.forEach(results, function(res){
console.log("Looped"); //this is just to verify that the then call below is executed only after all array objects are looped over.
});
} ,
error: function(error){
}
});
}
}
});
Here's the html code where I want to display the data:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body ng-controller="testCtrl">
{{test}}
{{results2}}
</body>
</html>
The results2 don't load up in the html.
Here is the console log.
testParse.js:46 This is done
2015-07-10 15:28:32.539testParse.js:46 This is done
2015-07-10 15:28:32.540testParse.js:46 This is done
2015-07-10 15:28:32.541testParse.js:46 This is done
2015-07-10 15:28:32.542testParse.js:56 Returning result as promised [object Object],[object Object],[object Object],[object Object]
You need to return data from your service and pass it to your controller. For ex:
app.controller('testCtrl', function ($scope, myService) {
var currentUser = Parse.User.current();
$scope.username = currentUser.getUsername();
$scope.test = "this";
myService.getEvaluatorData().then(function (response) {
console.log('response', response);
$scope.results2 = response;
});
});
app.factory('myService', function ($http, $q) {
return {
getEvaluatorData: function () {
var evaluators = Parse.Object.extend("Evaluators");
var query = new Parse.Query(evaluators);
return query.find({
success: function (results) {
return results;
},
error: function (error) {
return error;
}
});
}
}
});
Also, no point in calling this.getEvaluatorData($scope) in my opinion, when you can call the getEvaluatorData method directly
use $rootScope.result2 instead of $scope.result2
Related
Been trying to get this code to return http return data in $scope.top and use that data on the page to populate an element using {{top}}.
All variations I've tried either result in an empty $scope.top or $scope.top data arriving too late to be used on the page.
Latest attempt:
var app = angular.module("it", []);
app.factory('dataProvider', function($http){
return {
getTop: function(){
return $http.get("db.php");
}
}
});
app.controller('topList', function($log, $scope, dataProvider){
$scope.getTop = function(){
var promise = dataProvider.getTop();
promise.then(
function(data){
$scope.top = data.data;
},
function(errorData){
$log.error('failure loading', errorData);
});
}
});
What am I doing wrong?
I am self educating myself in angular js. For this i have created a project modelled after an actual project in my job
All get operation work fine but POST is giving me issue
My controller.js
var ngapp = angular.module('ngWebApp', ['angularUtils.directives.dirPagination']);
ngapp.controller('ngIndexController', function ($scope, ngDashboardService) {
$scope.exportData = function (selectedDataList) {
var getData = ngDashboardService.AddReportAudit(selectedDataList)
getData.then(function (result) {
alert(result.data);
}, function () {
alert('Error in getting records');
});
};
});
My service.js
angular.module('ngWebApp').service("ngDashboardService", function ($http) {
this.AddReportAudit = function (dataList) {
var response = $http({
method: "POST",
url: "/Home/AddReportAudit",
data: {
'dataList': JSON.stringify(dataList)
}
});
return response;
};
});
My code of JasonResult in HomeController
public JsonResult AddReportAudit(List<ADTOWebSMARTT_SSOData> dataList)
{
if (dataList != null)
{
using (HRMSystemEntities contextObj = new HRMSystemEntities())
{
var itemList = dataList.Where(x => x.IsChecked == true).ToList();
itemList.ForEach(a => a.DateChecked = DateTime.Now);
contextObj.SaveChanges();
return Json(new { success = true });
}
}
else
{
return Json(new { success = false });
}
}
The problem occurs here
public JsonResult AddReportAudit(List dataList)
For some reason the dataList on reaching AddReportAudit become empty i.e. list has zero element. dataList has 30 records in controller.js and service.js.
I am not sure why that is happening. is there a parsing that I am missing when json data comes from angular to c#
You are actually sending an Object, so the data that reaches your public JsonResult AddReportAudit(....isAnObject), but you are expecting it to be a list. Just change your controller code to the snippet below, it should work.
angular.module('ngWebApp').service("ngDashboardService",
function($http) {
this.AddReportAudit = function (dataList) {
var response = $http({
method: "POST",
url: "/Home/AddReportAudit",
data:JSON.stringify(dataList)
});
return response;
};
});
Solution for angular 1. Place your web service url and change the json data format as per your need. It works.
<!DOCTYPE html>
<html>
<head>
<title>Angular HTTP service</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<table>
<tr>
<th>S No</th>
<th>Source Name</th>
</tr>
<tr ng-repeat="res in result">
<td>{{$index + 1}}</td>
<td>{{res.source_name}}</td>
</tr>
</table>
<script type="text/javascript">
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope, $http){
$http.get("http://127.0.0.1:4000/all_source").then(function(res){
//console.log(res.data.result);
//console.log(res);
$scope.result = res.data.result;
});
});
</script>
</body>
</html>
I have a service to get (with array) all post from a server. I need to filter this array by id and show only this post in a single page.
In the service I have this code.
.service('PostAPI', function($http) {
this.getAll = function() {
return $http.get("ajax/getAllPosts.php");
}
this.getOne = function(data) {
return $http.get("ajax/searchPost.php?postID=" + data);
}
this.delete = function(data) {
if (confirm("Are you sure to delete this line?")) {
return $http.delete("ajax/deletePost.php?postID=" + data);
}
}
this.update = function(data) {
return $http.put("ajax/updatePost.php?postID" + data);
}
this.create = function() {
return $http.post("ajax/addPost.php");
}
})
In the controller
.controller("PostControlador", function($scope, $routeParams, PostAPI) {
GetPost();
$scope.title = "Editar post";
function GetPost() {
PostAPI.getOne($routeParams.id).success(function(data) {
$scope.post = data;
console.log($scope.post);
});
};
In post HTML I have this.
<div>
<div>{{post.TASK}}</div>
<div>{{post.STATUS}}</div>
<b>Back</b>
</div>
I'm not able to get any data to show in the page, and also, i have no errors in my console. ¿Any idea?
Check your ajax/searchPost.php?postID= api that is this api returning single object or array, If this api returning object than it should work but If you getting array of single element in response of api then in your api success code use first element of array by data[0].
Controller code
.controller("PostControlador", function($scope, $routeParams, PostAPI) {
GetPost();
$scope.title = "Editar post";
function GetPost() {
PostAPI.getOne($routeParams.id).success(function(data) {
$scope.post = data[0];
console.log($scope.post);
});
};
use then instaed of success. .then returns a promise so that you can handle the asynchrounous calls.
Also you are calling the getPost() method before function definition. So it may not get the promise.
call your getPost(), method after the function definition and check, so that it can receive the promise.
.controller("PostControlador", function($scope, $routeParams, PostAPI) {
$scope.title = "Editar post";
function GetPost() {
PostAPI.getOne($routeParams.id).then(function(data) {
$scope.post = data[0];
console.log($scope.post);
});
};
GetPost();
I can see my json data in the console and I want to view it on html page after clickbutton function. From my understaning I can either do a promise ($q) or then with http or ngResource. First I want to do http then migrate to ngResource. For some reason my scope is still undefined. Maybe it's a ng-init or ng-repeat I'm missing? Any ideas?
var app = angular.module('myApp', []);
app.factory('httpq', function($http, $q) {
return {
get: function() {
var deferred = $q.defer();
$http.get.apply(null, arguments)
.success(deferred.resolve)
.error(deferred.resolve);
return deferred.promise;
}
}
});
app.controller('myController', function($scope, httpq) {
httpq.get('http://localhost:8080/states')
.then(function(data) {
$scope.returnedData = data;
})
$scope.clickButton = function() {
$scope.returnedData;
}
});
view
<div data-ng-controller="myController">
<button data-ng-click="clickButton()">Get Data From Server</button>
<p>JSON Data : {{returnedData}}</p>
</div>
Use Ajax call
Service:
var demoService = angular.module('demoService', [])
.service('myService',['$http', function($http) {
this.getdata = function(entity){
var promise = $http({
method : 'POST',
url : 'services/entity/add',
data : entity,
headers : {
'Content-Type' : 'application/json'
},
cache : false
}).then(function (response) {
return response;
});
return promise;
};
}]);
Controller :
var demoService = angular.module('demoService', [])
.controller('myctr',['$scope','myService',function($scope,myService){
myService.getdata().then(function(response){
//Success
},function(response){
//Error
});
}]);
now you can see your json in controller success
$http itself is a promise, no need to create a new promise. Just return the $http.get wihoit the success written there and right the sucess fn in the controller itself. So your code will look like this:
app.factory('httpq', function($http) {
return {
get: function() {
return $http.get.apply(null, arguments);
}
}
});
Your controller:
app.controller('myController', function($scope, httpq) {
httpq.get('http://localhost:8080/states').then(function(data) {
$scope.returnedData = data;
})
$scope.clickButton = function() {
$scope.returnedData;
}
});
use
$scope.returnedData=JSON.parse(data);
It will give you values in JSON format
I have not worked with promise. But your factory code seems to be ok.
In controller declare your object first.
If it's just object declare it as
$scope.returnedData = {};
If it's array, declare it as
$scope.returnedData = [];
The the object will not be undefined and changes will affect in HTML
I'm trying to get a specific product by its id from a JSON file with products. I have some kind of problem as this question
AngularJS : get back data from a json array with an id
the code is similar. I read through that question and the accepted answer there, still can't figured this out. From what I understand the $scope.search() returns a promise which after success triggers the .then() to set get the correct person.
This line of code prints out the products array and also getting the product id from the url.
However it prints out twice in the console.
console.log($scope.products + $routeParams.productId);
app.js
var app = angular.module('gtbApp', [
'ngRoute',
'productControllers'
]);
// Setting up the routes with right controllers and partials
app.config(['$routeProvider', function($routeProvider){
$routeProvider
.when('/main', {
templateUrl: 'partials/product-grid.html',
controller: 'ProductController'
})
.when('/product/:productId', {
templateUrl: 'partials/product-detail.html',
controller: 'ProductDetailCtrl'
})
.otherwise({
redirectTo: '/main'
});
}]);
controllers.js
var app = angular.module('productControllers', []);
// For product-grid.html
app.controller('ProductController', ['$http', function($http){
var store = this;
store.products = [];
$http.get('products.json').success(function(data){
store.products = data;
});
}]);
// For product-detail.html
app.controller('ProductDetailCtrl', ['$scope', '$routeParams', '$http', function($scope, $routeParams, $http){
$scope.search = function() {
var url = 'products.json';
// Return a promise object
return $http.get(url).success(httpSuccess).error(function(){
console.log('Unable to retrieve info form JSON file.');
});
}
httpSuccess = function(response) {
$scope.products = response;
}
function getById(arr, id) {
for (var i = 0, len = arr.length; i < len; i++) {
if (arr[i].id === id) {
return arr[i];
}
}
}
$scope.search().then(function(){
// Prints out the products array and id twice
console.log($scope.products + $routeParams.productId);
$scope.product = getById($scope.products, $routeParams.productId);
// Prints out twice "undefined"
console.log($scope.product);
});
}]);
The main question is how to get specific product based on id why in "ProductDetailCtrl"
$scope.product = getById($scope.products, $routeParams.productId);
doesn't work.
Thanks in advance!
Update:
Found out why $scope.product is undefined, it is just because the $routeParams.productId is a string, and in getById() need a integer in second args.
However I don't know why console.log($scope.product); prints out twice.
I don't really understand what your main question is here. But anyways. When you use the $http service it will return a promise, which you eventually will have to unwrap. What you are doing in your code is that you are unwrapping it twice. Which is fine.
With $http response you can either use 'success'/'error' or just 'then' which can take a success and an error callback. Which means you could either unwrap in the search function or after you call the search function.
$scope.search = function() {
var url = 'products.json';
$http.get(url)
.success(function(data){
$scope.product = getById($scope.products, $routeParams.productId);
})
.error(function() {
console.log('Unable to retrieve info form JSON file.');
});
}
You could also do something like:
$scope.search = function() {
var url = 'products.json';
return $http.get(url);
}
$scope.search().then(function(data) {
$scope.product = getById(data, $routeParams.productId);
}, errorCallback);
And the below would achieve the same result
$scope.search = function() {
var url = 'products.json';
return $http.get(url);
}
$scope.search()
.success(function(data) {
$scope.product = getById(data, $routeParams.productId);
})
.error(errorCallback);
or reference the promise:
$scope.search = function() {
var url = 'products.json';
return $http.get(url);
}
var dataPromise = $scope.search();
dataPromise.then(function(data) {
$scope.product = getById(data, $routeParams.productId);
}, errorCallback);
What you need to know is that as long as you're returning something within a success/error/then function it will return a promise which you will have to unwrap in order to get the data.
You should be either using the .success() and .error() on the $http-promise or only then .then()
Do it like this:
app.controller('ProductController', ['$scope', '$routeParams', '$http', function($scope, $routeParams, $http){
$scope.search = function() {
var url = 'products.json';
// Return a promise object
return $http.get(url);
}
.....
$scope.search()
.success(function(data){ // --> data is the products.json
... // handle the successfull call
} );
.error(function(...) {
... // handle the error
} );
// or:
$scope.search().then(
function(data){ // --> data is the products.json
... // handle the successfull call
},
function(...) {
... // handle the error
});
}]);