Angularjs goes into infinite loop while firing $http function - angularjs

My app goes into infinite loop while firing $http get method inside a function
In my controller I am using POST and getting data from API after authorization and displaying it.
var app = angular.module('myApp', []);
app.controller('ctrl1', function($scope, $http) {
$http({
url: 'url',
method: "POST",
data: 'postData',
headers: {
'Authorization': 'value'
}
})
.then(function(response) {
$scope.hotels = response.data;
});
$scope.imagePath = function(id) {
console.info(id);
if (id) {
$http({
method: 'GET',
url: 'url=' + id
})
.then(function(response) {
var imgdata = response.data;
console.info(imgdata);
var imgdata1 = imgdata.data.image_name;
return "url" + imgdata1;
});
}
};
});
In my img ng-src I have to call data from another API from the key exterior_image which I am passing in my function but it goes into an infinite loop. Also I know I have to use angular forEach in imgdata1.
<div ng-controller='ctrl1'>
<select ng-options='item as item.hotel_name for item in hotels.data' ng-model='hotel'></select>
<h1>{{hotel.hotel_name}}</h1>
<p>{{hotel.hotel_description}}</p>
<img ng-src="{{imagePath(hotel.exterior_image)}}">
</div>

Try this in your Controller:
var app = angular.module('myApp', []);
app.controller('ctrl1', function ($scope, $http) {
$scope.current_Hotel = {
hotel_name: "Default Value Here",
hotel_description: "Default Value Here",
exterior_image: "Default id here",
image_url: "Default url here"
};
$http({
url: 'url',
method: "POST",
data: 'postData',
headers: {
'Authorization': 'value'
}
}).then(function (response) {
$scope.hotels = response.data;
});
$scope.selectHotel = function () {
$http({
method: 'GET',
url: 'url=' + $scope.current_Hotel.exterior_image
}).then(function (response) {
var imgdata = response.data;
var imgdata1 = imgdata.data.image_name;
$scope.current_Hotel.image_url = "url" + imgdata1;
});
};
});
and this:
<div ng-controller='ctrl1'>
<select ng-options='item as item.hotel_name for item in hotels.data' ng-model='current_Hotel'></select>
<h1>{{current_Hotel.hotel_name}}</h1>
<p>{{current_Hotel.hotel_description}}</p>
<img ng-src="{{current_Hotel.image_url}}">
</div>

Related

SyntaxError: Unexpected token U in JSON at position 0 when i make post request

I am making a post request to an api with submit() function which is attached to a ng-click directive sending the data in JSON format, it returns this error.
It is running fine on postman so the error is on client side only.
Also the email and selectedIds variables are not empty.
Here is my controller file:
app.controller('categoryController', ['$scope', '$rootScope', '$sce', '$http', '$timeout','$window', function($scope, $rootScope, $sce, $http, $timeout, $window) {
$scope.allCategories = {};
$http({
method: 'GET',
url: 'http://qubuk.com:8081/api/v1/alltag'
})
.then(function (data) {
// console.log("DATA:" + JSON.stringify(data.data.categories[0].displayName));
// console.log("DATA category:" + JSON.stringify(data.data.categories));
$scope.allCategories = data.data.categories;
});
$scope.selectedIds = [];
$scope.change = function(category, active){
if(active){
$scope.selectedIds.push(category.id);
}else{
$scope.selectedIds.splice($scope.selectedIds.indexOf(category.id), 1);
}
// console.log("SELECTED IDS:" + $scope.selectedIds);
};
$scope.email = "faiz.krm#gmail.com"
console.log("email is "+ $scope.email);
$scope.submit = function () {
var tagsData = {"emailId": $scope.email,
"tagsId": $scope.selectedIds};
console.log("tagsData:" + JSON.stringify(tagsData));
$http({
method:'POST',
url: 'http://qubuk.com:8081/api/v1/user/update/tags',
data: tagsData
})
.then(function (data) {
console.log("Ids sent successfully!");
alert("successful");
$window.location.href = '/app/#/feed';
})
};
// console.log("amm Categories:" + JSON.stringify($scope.allCategories));
}]);
edit: the response is not a JSON object... it is a string. I do think error is due to this only... how can i resolve it on the front end...
Try to add:
headers : { 'Content-Type': 'application/x-www-form-urlencoded'}
to your request:
$http({
method:'POST',
url: 'http://qubuk.com:8081/api/v1/user/update/tags',
data: tagsData,
headers : { 'Content-Type': 'application/x-www-form-urlencoded'}
})
Alternately try to pass a stringify data:
$http({
method:'POST',
url: 'http://qubuk.com:8081/api/v1/user/update/tags',
data: JSON.stringify(tagsData),
headers: {'Content-Type': 'application/json'}
})

Angular - Pass input value to factory $http query parameter

I have created a factory to run an $http GET method. I need to add an input value to the URL pulling in the JSON but I'm having trouble passing it from the controller. I can see that the URL is being created correctly, I am just missing the "query" parameter from the form input field.
Here is my HTML block:
<input type="string" class="form-control" ng-model="getMovie.title">
Here is my factory and controller:
var app = angular.module('app', []);
app.factory("getMovie", ['$http',function($http){
var obj = {};
var url = "https://api.nytimes.com/svc/movies/v2/reviews/search.json";
obj.getMovieInfo = function(){
return $http({
url: url,
method: "GET",
params:{
query: this.title, // This is the value I need
api_key: "68094e1974e7984c256beb1653319915:3:33678189",
callback: "JSON_CALLBACK"
},
headers: {
"Content-Type" : "application/json"
}
}).then(function successCallback(response) {
this.movieReviews = response.data.results;
}, function errorCallback(response) {
console.log("Nothing to see here...");
});
}
return obj;
}]);
app.controller('moviesCtrl', ["$scope", "getMovie", function($scope, getMovie){
$scope.findMovie = function(){
getMovie.getMovieInfo().then(function(response){
$scope.results = response;
});
}
}]);
Thanks!
You can send the title as parameter to the factory method.
<input type="string" class="form-control" ng-model="title">
var app = angular.module('app', []);
app.factory("getMovie", ['$http',function($http){
var obj = {};
var url = "https://api.nytimes.com/svc/movies/v2/reviews/search.json";
obj.getMovieInfo = function(title){
return $http({
url: url,
method: "GET",
params:{
query: title, // This is the value I need
api_key: "68094e1974e7984c256beb1653319915:3:33678189",
callback: "JSON_CALLBACK"
},
headers: {
"Content-Type" : "application/json"
}
}).then(function successCallback(response) {
this.movieReviews = response.data.results;
}, function errorCallback(response) {
console.log("Nothing to see here...");
});
}
return obj;
}]);
app.controller('moviesCtrl', ["$scope", "getMovie", function($scope, getMovie){
$scope.findMovie = function() {
getMovie.getMovieInfo($scope.title).then(function(response){
$scope.results = response;
});
}
}]);
I recommend you dont use this . If you want use controllerAs syntax , use like this . You can see more in here
https://github.com/johnpapa/angular-styleguide/tree/master/a1#controllers
app.factory("getMovie", ['$http',function($http){
var vm = this
vm.getMovie ={};
And in ajax
return $http({
url: url,
method: "GET",
params:{
query: vm.getMovie, // This is the value I need
api_key: "68094e1974e7984c256beb1653319915:3:33678189",
callback: "JSON_CALLBACK"
},
headers: {
"Content-Type" : "application/json"
}
}).then(function successCallback(response) {
vm.movieReviews = response.data.results;
}, function errorCallback(response) {
console.log("Nothing to see here...");
});
}
return obj;
}]);

how to pass null as value of a variable in data of ajax method

I want to send a null value in the "mailID" field as email id is not a required field in the form.
var app = angular.module('MyApp', [])
app.controller('MyController', function($scope, $http, $window) {
$scope.ButtonClick = function() {
var post = $http({
method: "POST",
url: "url",
dataType: 'json',
data: {
name: $scope.Name,
mailID: $scope.MailID,
},
headers: {
"Content-Type": "application/json"
}
});
post.success(function(data, status) {
$window.alert(data.d);
});
post.error(function(data, status) {
$window.alert(data.Message);
});
}
});
When the MailID is not set, just don't send it along your data object.
Your server needs to check wheter the MailID is available or not.
var app = angular.module('MyApp', [])
app.controller('MyController', function($scope, $http, $window) {
$scope.ButtonClick = function() {
var data = {};
data.name = $scope.Name;
angular.isDefined($scope.MailID) data.MailID = $scope.MailID;
var post = $http({
method: "POST",
url: "url",
dataType: 'json',
data: data,
headers: {
"Content-Type": "application/json"
}
});
post.success(function(data, status) {
$window.alert(data.d);
});
post.error(function(data, status) {
$window.alert(data.Message);
});
}
});

How to transfer data between controllers

I am trying to transfer data between controllers.
So this is my first controller that fetches data first when page loads using http-
function GetController($scope, $http) {
$http.defaults.useXDomain = true;
$http({
method: 'POST', url: serviceUrl + '/GetProductsByCategoryOrName', headers: {
'Authorization': apiKey
},
data: { "query": "grocery", "categoryId": "976759", "pageIndex": 0, "sortDirection": "asc" }
}).then(function successCallback(response) {
$scope.products = response.data;
}).then(function errorCallback(error) {
})
}
the view looks like-
<div ng-controller="GetController">
<div class="mdl-cell" ng-repeat="product in products">
<img src="{{product.largeImage}}" />
<div class="mdl-card__title">
<h6 class="mdl-card__title-text">{{product.name}}</h6>
</div>
</div>
</div>
</div>
Where now my need is to rebind this HTML with the same request but different parameters. So I created another controller for this job-
function searchProductsController($scope, $http) {
$http.defaults.useXDomain = true;
$scope.searchText = "";
$scope.submit = function () {
$http({
method: 'POST', url: serviceUrl + '/GetProductsByCategoryOrName', headers: {
'Authorization': apiKey
},
data: { "query": $scope.searchText, "categoryId": "976759", "pageIndex": 0, "sortDirection": "asc" }
}).then(function successCallback(response) {
$scope.products = response.data; //how to bind this with GetController's $scope.products??
}).then(function errorCallback(error) {
});
}
};
What is needed-
I want to bind $scope.products of searchProductsController to GetController's $scope.products so that it renders in view.
I don't have any idea how to do this at the moment as I am very new to angular.
However, I've given a try to create service for transferring purpose but don't really have idea how to integrate it with it.
Edit-
I've edited controller methods as #Varkal suggested using service, Still couldn't get the problem resolved.
var app = angular.module("productsApp", [])
.service("serviceProvider", function ($http) {
this.getDatas = function getDatas(data) {
return $http({
method: 'POST', url: serviceUrl + '/GetProductsByCategoryOrName', headers: {
'Authorization': apiKey
},
data: data
})
}
return this
});
function GetController($scope, serviceProvider) {
var data = { "query": "grocery", "categoryId": "976759", "pageIndex": 0, "sortDirection": "asc" };
serviceProvider.getDatas(data).then(function (response) {
$scope.products = response.data.data;
});
}
function searchProductsController($scope, serviceProvider) {
var data = { "query": $scope.searchText, "categoryId": "976759", "pageIndex": 0, "sortDirection": "asc" };
$scope.submit = function () {
serviceProvider.getDatas(data).then(function (response) {
console.log(response.data.data);
$scope.products = response.data.data;
});
}
};
When you need to share things betweens controller, those things should be in a service
For example :
angular.service("datasService", function ($http) {
this.getDatas = function getDatas() {
return $http({
method: 'POST', url: serviceUrl + '/GetProductsByCategoryOrName', headers: {
'Authorization': apiKey
},
data: { "query": "grocery", "categoryId": "976759", "pageIndex": 0, "sortDirection": "asc" }
})
}
return this
});
And in your controller :
function GetController($scope, datasService) {
datasService.getDatas().then(function(){
$scope.products = response.data
}
}
This is a very simple example : you can also store your datas in the service, so call $http only once, and add a method to refresh the product list
This is the most "Angular-ly" way of share datas between controllers, but you can also use localStorage (ngStorage can help you here)
If you have 2 views with 2 controllers, it is possible to share the $scope variables(data) between controllers through services and factory.But, the $scope variables are local to the controller itself so set the data to the service or factory to know about that particular variable.I prefer using factory, easy and smooth as butter. If you are using the service or factory in a separate file you need to include the file in index.html.
app.controller('Ctrl1', function($scope, myService, $state) {
$scope.variable1 = "One";
myService.set($scope.variable1);
$state.go('app.thepagewhereyouwanttoshare'); //go to the page where you want to share that variable.
});
app.controller('Ctrl2', function($scope, myService) {
console.log("shared variable " + myService.get());
});
.factory('myService', function() {
function set(data) {
products = data;
}
function get() {
return products;
}
return {
set: set,
get: get
}
})
Also, you can use localstorage for the purpose of sharing data.localStorage comes with angularjs so no need to inject any additional dependency in the controller or app.
In the controller which has to pass data:
localStorage.setItem("products",$scope.products);
In the controller where you to access data:
localStorage.getItem("products");
In your case:
function GetController($scope, $http) {
$http.defaults.useXDomain = true;
$http({
method: 'POST', url: serviceUrl + '/GetProductsByCategoryOrName', headers: {
'Authorization': apiKey
},
data: { "query": "grocery", "categoryId": "976759", "pageIndex": 0, "sortDirection": "asc" }
}).then(function successCallback(response) {
$scope.products = response.data;
localStorage.setItem("products",$scope.products);
}).then(function errorCallback(error) {
})
}
function searchProductsController($scope, $http) {
$http.defaults.useXDomain = true;
$scope.searchText = "";
$scope.submit = function () {
$http({
method: 'POST', url: serviceUrl + '/GetProductsByCategoryOrName', headers: {
'Authorization': apiKey
},
data: { "query": $scope.searchText, "categoryId": "976759", "pageIndex": 0, "sortDirection": "asc" }
}).then(function successCallback(response) {
$scope.products = response.data; //how to bind this with GetController's $scope.products??
$scope.productsFromGetController = localStorage.getItem("products");
}).then(function errorCallback(error) {
});
}
};
Using the factory, you need to navigate to the page where you want to get the data after you set it since the data set can be overwritten by another set in another views.
FINAL UPDATE: Using service and factory
<html>
<head>
<title>Angular JS Controller</title>
<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app = "app" >
<div ng-controller="searchProductsController">
<input ng-model="searchText"/>
<button ng-click="setPlace(searchText)">Enter Search id</button>
</div>
<div ng-controller="GetController">
<div ng-repeat="product in products">
<h3>{{product.name}}</h3>
</div>
</div>
</div>
<script>
var app = angular.module('app', []);
app.factory("Service", function () {
var data;
function getdata() {
return data;
}
function setdata(newdata) {
data = newdata;
}
return {
getdata: getdata,
setdata: setdata,
}
}).factory("dataService",function($http){
return{
getComments:function (roomid){
if(roomid==1){
var data = [{"name":"alex","place":"kathmandu"},{"name":"god","place":"seattle"}];
return data;
}
if(roomid==2)
{
var newdata = [{"name":"newname","place":"kathmandu"},{"name":"newname2","place":"seattle"}];
return newdata;
}
}
}
});
app.controller('searchProductsController',function($scope, Service,$http,dataService) {
var data = dataService.getComments(1);
Service.setdata(data);
$scope.setPlace = function (searchText) {
var newdata = dataService.getComments(searchText);
Service.setdata(newdata);
}
})
.controller('GetController',function($scope, Service) {
$scope.$watch(function () {
return Service.getdata();
}, function (value) {
$scope.products = value;
});
})
</script>
</body>
</html>
Update regarding your unworking plunker:
It is closest i can get with the mock of your controller:
http://plnkr.co/edit/p9qY1IIWyzYGLehsIOPr?p=preview

AngularJS - ng-repeat - using parent repeat data in child http request

I have what would seem to be a simple problem with AngularJS - apologies if so. I'm new and have searched all over and can't quite find an answer to what I want to do.
Basically I have a $http request that is getting a list of 'Cards' from a server which I'm then using ng-repeat to build in the HTML. I then want to populate those Cards with a number of 'Metrics' - also retrieved from the server. I have a controller for the 'Cards' (parents) and a separate controller for the 'Metrics' (children).
My issue is that I can't work out how to reference the ID of the parent 'Card' when making the child $http request.
Below is the HTML & JS that I am using - any help would be appriciated:
HTML:
<div class="Dashboard container-fluid" ng-controller="DahsboardCardController as Dashboard">
<div ng-repeat="Card in Dashboard.DashboardCards">
<div class="DashboardCard card">
{{Card.CardDisplayName}}
<div class="DashboardCardBody" ng-controller="DahsboardMetricController as Metric">
<div ng-repeat="Metric in Metric.DashboardMetrics">
{{Metric.MetricDisplayName}}
</div>
</div>
</div>
</div>
JS:
(function () {
var app = angular.module('OtterDashboard', [ ]);
app.controller('DahsboardCardController', [ '$http', function($http) {
//Declare a varaible for the data
var DashboardCards = this;
//Set the varaiable to an empty array to receive the data
DashboardCards.DashboardCards = [ ];
$http({
//Request the data
method: 'GET',
dataType: 'jsonp',
url: '/api.svc/tbl_Card',
useDefaultXhrHeader: false,
headers: {'Content-type': 'application/json'},
headers: {'Accept': 'application/json;odata=light;q=1,application/json;odata=verbose;q=0.5'},
crossDomain: true,
}).then(function successCallback(data) {
//The data was sucessfully received, populate the variable with it
DashboardCards.DashboardCards = data.data.d.results;
}, function errorCallback(response) {
//There was an error
console.log('Card data could not be retrieved');
});
}]);
app.controller('DahsboardMetricController', ['$http', function($http, Card) {
//Declare a varaible for the data
var DashboardMetrics = this;
//Set the varaiable to an empty array to receive the data
DashboardMetrics.DashboardMetrics = [ ];
$http({
//Request the data
method: 'GET',
dataType: 'jsonp',
url: '/api.svc/DashboardMetric?Card=%27' + **???reference to parent card ID???** + '%27',
useDefaultXhrHeader: false,
headers: {'Content-type': 'application/json'},
headers: {'Accept': 'application/json;odata=light;q=1,application/json;odata=verbose;q=0.5'},
crossDomain: true,
}).then(function successCallback(data) {
//The data was sucessfully received, populate the variable with it
DashboardMetrics.DashboardMetrics = data.data.d.results;
}, function errorCallback(response) {
//There was an error
console.log('Metric data could not be retrieved');
});
}]);
})();
Thank you!
EDIT 1
Use a service for shared variable between controllers. Look the example:
app.controller('DahsboardCardController', ['$http', function($http, $sharedResource) {
var DashboardCards = this;
DashboardCards.DashboardCards = [ ];
$http({
method: 'GET',
dataType: 'jsonp',
url: '/api.svc/tbl_Card',
useDefaultXhrHeader: false,
headers: {'Content-type': 'application/json'},
headers: {'Accept': 'application/json;odata=light;q=1,application/json;odata=verbose;q=0.5'},
crossDomain: true,
}).then(function successCallback(data) {
DashboardCards.DashboardCards = data.data.d.results;
$sharedResource.set("id", "<pass id value>");
}, function errorCallback(response) {
console.log('Card data could not be retrieved');
});
}]);
app.controller('DahsboardMetricController', ['$http', function($http, Card, $sharedResource) {
var DashboardMetrics = this;
DashboardMetrics.DashboardMetrics = [];
$http({
method: 'GET',
dataType: 'jsonp',
url: '/api.svc/DashboardMetric?Card=%27' + $sharedResource.get("id") + '%27',
useDefaultXhrHeader: false,
headers: {'Content-type': 'application/json'},
headers: {'Accept': 'application/json;odata=light;q=1,application/json;odata=verbose;q=0.5'},
crossDomain: true,
}).then(function successCallback(data) {
DashboardMetrics.DashboardMetrics = data.data.d.results;
}, function errorCallback(response) {
console.log('Metric data could not be retrieved');
});
}]);
app.factory('$sharedResource', function () {
var property = {};
return {
get: function (key) {
return property[key];
},
set: function(key, value) {
property[key] = value;
}
};
});
EDIT 2
When working with angularjs is recomended use a one object for print object in table. Why this is a beautiful s2.
Look this example. To help you in development. Use the sample function pass the parentId in load(CardId). This function will run in the page load.
I too fix code html. You used the alias controller before input field of same.
var app = angular.module("App", []);
app.controller('DahsboardCardController', ['$scope', function($scope) {
$scope.DashboardCards = [{
CardId: "111",
CardDisplayName: "Card 1"
}, {
CardId: "222",
CardDisplayName: "Card 2"
}, {
CardId: "333",
CardDisplayName: "Card 3"
}];
}
]);
app.controller('DahsboardMetricController', ['$scope', function($scope) {
$scope.load = function(CardIdParent) {
console.log(CardIdParent);
};
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="App" class="Dashboard container-fluid" ng-controller="DahsboardCardController as Dashboard">
{{Dashboard.DashboardCards}}
<div ng-repeat="Card in DashboardCards">
<div class="DashboardCard card">
{{Card.CardDisplayName}}
<div class="DashboardCardBody" ng-controller="DahsboardMetricController as Metric" ng-init="load(Card.CardId)">
This a id parent: {{Card.CardId}}
<div ng-repeat="MetricItem in DashboardMetrics">
{{MetricItem.MetricDisplayName}}
</div>
</div>
</div>
</div>
</div>

Resources