So i'm busy with a webapplication and i'm stuck now with parsing an object. What I just tried to do is getting the ID of all results but it gives me undefined back in my console.
What did i try:
var app = angular.module("DB", []);
app.controller("Controller", function($scope, $http) {
$http.defaults.headers.common["Accept"] = "application/json";
$http.get('api_url').
success(function(data, status, headers, config) {
$scope.games = data.results;
$scope.id = data.results.id;
//Do i need a foreach here because it doesn't loop through all records and it gives me undefined.
$http.get('http:/api/id/' + $scope.id + '?api_key=', function(e){
}).
success(function(data, status, headers, config) {
$scope.details = data;
console.log(data);
//this returns the complete JSON
});
}).
error(function(data, status, headers, config) {
//handle errors
});
});
the first http.get loops through a JSON like:
"results": [
{
"easy": false,
"id": 1,
"title": "title",
},
{
"easy": false,
"id": 2,
"title": "title",
},
{
"easy": true,
"id": 2,
"title": "title",
}
]
and what the second on needs to do is get all of the ID's from the JSON and start a new GET:
$http.get('http:/api/id/' + $scope.id + '?api_key=', function(e){
}).
success(function(data, status, headers, config) {
$scope.details = data;
console.log(data.data);
});
})
the problem is that is, is that $scope.id = data.results.id; is returing nothing, do i need a foreach or something to loop through it all?
And displaying it i did try:
<div ng-repeat="detail in details">
{{ detail }}
{{ detail.adult }}
</div>
but is does not display anything (fyi i changed $scope.id = data.results.id; to $scope.id = data.results[0].id; to test it)
the JSON for the second GET looks like:
{
"adult": false,
"collection": {
"id": 131295,
"name": "Collection",
},
"levels": [{
"id": 28
}, {
"id": 12
}, {
"id": 878
}],
"homepage": "google",
"id": 100402,
"overview": "lorem ipsum"
}
i can't access the object with {{ detail.adult }} for example.
The reason why data.results.id is returning nothing is because data.results is an Array of objects. If what you want is an Array with the IDs of the objects of data.results you could do it like this:
var resultIDs = data.results.map(function(result){return result.id;});
I'm not sure, but I think that this is what you want:
var app = angular.module("DB", []);
app.controller("Controller", function($scope, $http) {
$scope.details = [];
$http.defaults.headers.common["Accept"] = "application/json";
$http.get('api_url').
success(function(data, status, headers, config) {
$scope.games = data.results;
for(var i =0;i<$scope.games.lenght;i++){
$http.get('http:/api/id/' + $scope.games[i].id + '?api_key=', function(e){
}).
success(function(data, status, headers, config) {
$scope.details.push(data);
});
}
}).
error(function(data, status, headers, config) {
//handle errors
});
});
However I would check if the API that you are using has a method that accepts an array of IDs instead of a single ID, so that you don't have to iterate like that.
If this API is a RESTful service you could do it without iterating, like this:
var app = angular.module("DB", []);
app.controller("Controller", function($scope, $http) {
$scope.details = [];
$http.defaults.headers.common["Accept"] = "application/json";
$http.get('api_url').
success(function(data, status, headers, config) {
$scope.games = data.results;
var resultIDs = data.results.map(function(result){return result.id;});
$http.get('http:/api?id=' + resultIDs.join(',') + '?api_key=', function(e){
}).
success(function(data, status, headers, config) {
$scope.details = data;
});
}).
error(function(data, status, headers, config) {
//handle errors
});
});
Related
I have a select list box, and the I have a button. Based on the button selectId, I have to filter the model which showing in the select list box.
The problem here is that the model only updates when I click this button twice. I have a filter function in GetFormsClicked which have logic regarding this.
My Angular controller is the following:
(function() {
var controllerId = 'GroupsController';
ig.app.controller(controllerId, ['$scope', '$log', '$http', '$compile', 'fileRvwQuestSvc', 'DataSvc',
function($scope, $log, $http, $compile, fileRvwQuestSvc, DataSvc) {
$scope.FrequencyMap = {
1: "Annual",
2: "Monthly",
3: "Half Year"
};
$scope.FormMap = {
1: "CMSMISC",
2: "CMSFPEA",
3: "CMSPIID",
5: "CMSMSR",
7: "CMSCOI"
}
$scope.GetAllGroupForms = function(Id) {
var url = '/GroupForm/Details/' + Id;
$scope.loading = true;
DataSvc.getAjaxData(url)
.then(function(data) {
//success
$scope.GroupForm = data.data;
$scope.GroupFormBack = data.data;
$scope.loading = false;
}, function(httpStatus) {
//failed
$scope.hasErrors = true;
if (httpStatus === 404) {
$scope.errorMessage = "Couldn't retrieve Users Info";
} else {
$scope.errorMessage = 'The system could not process your request, please try again or contact the system administrator.';
}
$log.warn(httpStatus);
$scope.loading = false;
});
};
$scope.availableFormsTestOriginal = [
{
"Id": null,
"GroupId": null,
"FormId": 1,
"SortOrder": null,
"Frequency": 1,
"IsCollapsed": false,
"IsDeleted": false
},
{
"Id": null,
"GroupId": null,
"FormId": 2,
"SortOrder": null,
"Frequency": 1,
"IsCollapsed": false,
"IsDeleted": false
},
{
"Id": null,
"GroupId": null,
"FormId": 3,
"SortOrder": null,
"Frequency": 1,
"IsCollapsed": false,
"IsDeleted": false
}
]
var AddGroupForm = function() {
$scope.loading = true;
var url = '/GroupForm/Create/';
DataSvc.AddFormData(url, $scope.GroupForm)
.then(function(data) {
//success
$scope.loading = false;
//$scope.successMessage = "Form Saved Successfully";
$scope.successMessage = "GroupForm Updated Successfully";
}, function(httpStatus) {
//failed
$scope.hasErrors = true;
if (httpStatus === 404) {
$scope.errorMessage = "Couldn't retrieve Users Info";
} else {
$scope.errorMessage = 'The system could not process your request, please try again or contact the system administrator.';
}
$log.warn(httpStatus);
$scope.loading = false;
});
}
$scope.filterailableforms = function() {
for (i = 0; i < $scope.availableFormsTest.length; i++) {
for (j = 0; j < $scope.GroupForm.length; j++) {
if ($scope.availableFormsTest[i].FormId === $scope.GroupForm[j].FormId && $scope.availableFormsTest[i].Frequency === $scope.GroupForm[j].Frequency) {
$scope.availableFormsTest.splice(i, 1);
}
}
}
}
activate();
$scope.GetFormsClicked = function(selectid) {
$scope.availableFormsTest = angular.copy($scope.availableFormsTestOriginal);
$scope.GetAllGroupForms(selectid);
$scope.updateavailableforms(selectid);
$scope.filterailableforms();
}
function activate() {
$scope.loading = false;
$scope.GetAllGroup();
}
}
]);
})();
My view code is as follows:
<button ng-click="GetFormsClicked(selectedId)">Select Group <span style="color:black"></span></button>` <select size="5" multiple ng-model="available" ng-options="x as FormMap[x.FormId]+' --- '+FrequencyMap[x.Frequency] for x in availableFormsTest" style="width: 400px"></select>
My dataser code:
ig.app.factory('DataSvc', [
'$http', '$q', '$log',
function ($http, $q, $log) {
return {
getAjaxData: function (CtrlUrl) {
var deferred = $q.defer();
var rnd = ((Math.random() * 1000000) + 1);
$http({
method: 'GET',
url: CtrlUrl + "/?r=" + rnd
})
.then(function (data, status, headers, config) {
deferred.resolve(data, status, headers, config);
},
function (data, status, headers, config) {
$log.warn(data, status, headers(), config);
deferred.reject(status);
});
return deferred.promise;
},
AddFormData: function (CtrlUrl, model) {
var deferred = $q.defer();
$http.post(CtrlUrl, model).then(function (data, status, headers, config) {
deferred.resolve(data, status, headers, config);
},function (data, status, headers, config) {
$log.warn(data, status, headers(), config);
deferred.reject(status);
});
return deferred.promise;
},
UpdateFormData: function (CtrlUrl, model) {
var deferred = $q.defer();
$http.post(CtrlUrl, model).then(function (data, status, headers, config) {
deferred.resolve(data, status, headers, config);
},function (data, status, headers, config) {
$log.warn(data, status, headers(), config);
deferred.reject(status);
});
return deferred.promise;
}
}
}]);
Your problem is due to the use of ng-model="variable".
The rule is "always have a dot in your ng-model", you should have a ng-model="obj.variable" with the correct obj.
The reason is that each directive with scope:true inherits the parent scope, and the "variable" you are editing isn't copied back to the parent.
The problem is due to the fact that the strings are copied by value.
By using an object, all the scope will reference the same variable.
I'm at a loss on this. I have checked the forums and can't seem to find a solution.
I'm working on creating an ionic app to pull json feeds into the app and have them process. I have one feed setup, in one angular module, that is pulling some data perfectly fine. But when I try to create this second module, the feed var it errors, but if I hard code the URL in the $http.get it works fine.
This code errors with TypeError: Cannot read property 'protocol' of undefined:
angular.module('mwre.services', [])
.factory('PropertyFeed', function($http) {
var listings = {
residential: "http://somewebsite/api-access/get/mostwantedrealestate/categories/1?limit=2",
land: "http://somewebsite/api-access/get/mostwantedrealestate/categories/1?limit=2"
};
var content = "http://somewebsite/api-access/get/mostwantedrealestate/properties/"
return {
getPropertiesContent: function(section, successCallback, errorCallback){
$http.get(listings[section])
.success(function(data, status, headers, config) {
successCallback(data);
})
.error(function(data, status, headers, config) {
errorCallback(status);
});
},
getPropertyItem: function(id, successCallback, errorCallback){
$http.get(smalldesc + id)
.success(function(data, status, headers, config) {
successCallback(data);
})
.error(function(data, status, headers, config) {
errorCallback(status);
});
}
}
});
However, making the following change to the $http.get works:
angular.module('mwre.services', [])
.factory('PropertyFeed', function($http) {
var listings = {
residential: "http://somewebsite/api-access/get/mostwantedrealestate/categories/1?limit=2",
land: "http://somewebsite/api-access/get/mostwantedrealestate/categories/1?limit=2"
};
var content = "http://somewebsite/api-access/get/mostwantedrealestate/properties/"
return {
getPropertiesContent: function(section, successCallback, errorCallback){
$http.get("http://somewebsite/api-access/get/mostwantedrealestate/categories/1?limit=2")
.success(function(data, status, headers, config) {
successCallback(data);
})
.error(function(data, status, headers, config) {
errorCallback(status);
});
},
getPropertyItem: function(id, successCallback, errorCallback){
$http.get(smalldesc + id)
.success(function(data, status, headers, config) {
successCallback(data);
})
.error(function(data, status, headers, config) {
errorCallback(status);
});
}
}
});
I can't seem to figure out what I've got wrong in my code.
Here is the controller that is running that feed. It works perfectly fine when the URL is hardcoded.
angular.module('mwre.controllers', [])
.controller('PropertiesCtrl', function($scope, $state, $stateParams, $log, $ionicPopup, PropertyFeed) {
$scope.items = [];
$scope.successGetPropertiesContent = function(data) {
$scope.maxIntro = 100;
$scope.items = data.properties;
for (var i = 0; i < $scope.items.length; i++) {
$scope.items[i].smalldesc = $scope.items[i].smalldesc.replace(/<[^>]+>/gm, '');
if ($scope.items[i].smalldesc.length > $scope.maxIntro) {
$scope.items[i].smalldesc = $scope.items[i].smalldesc.substr(0, $scope.maxIntro) + '...';
}
}
};
$scope.errorGetPropertiesContent = function(status) {
$scope.showAlert = function() {
var alertPopup = $ionicPopup.alert({
title: 'Error reading property category content',
template: 'Please check your network connection'
});
alertPopup.then(function(res) {
$log.debug('Error reading property category content');
});
};
$scope.showAlert();
};
PropertyFeed.getPropertiesContent($stateParams.propertiesId, $scope.successGetPropertiesContent, $scope.errorGetPropertiesContent);
$scope.goToContent = function(id) {
$state.go('app.properties', { propertiesId: id });
};
})
.controller('PropertyCtrl', function($scope, $state, $stateParams, $log, $ionicPopup, PropertyFeed) {
$scope.item = null;
$scope.successGetPropertyItem = function(data) {
$scope.item = data;
};
$scope.errorGetPropertyItem = function(status) {
$scope.showAlert = function() {
var alertPopup = $ionicPopup.alert({
title: 'Error reading property listing',
template: 'Please check your network connection'
});
alertPopup.then(function(res) {
$log.debug('Error reading property listing');
});
};
$scope.showAlert();
};
PropertyFeed.getPropertyItem($stateParams.propertyId, $scope.successGetPropertyItem, $scope.errorGetPropertyItem);
});
I have a JSON file which has a user list. I want to get only a specific user from the list, and display it on an index page using Angular. I've searched a lot, but can't get a good answer. The list has to be in a JSON file, not in a JS file.
sampleApp.controller('userInfo', ['$scope', '$http', '$log', '$filter', function($scope, $http, $log,$filter) {
$scope.results = '';
$http.defaults.headers.common['X-Custom-Header'] = 'Angular.js';
$http.get('data/registered-user-list.json').
success(function(data, status, headers, config) {
$scope.results = data;
})
.error(function(data, status, headers, config) {
// log error
});
}]);
The JSON file:
{ "results": [
{
"usernumber": "1",
"userid": "manojsoni",
"userpassword": "password",
"useremail": "manojsoni.online#gmail.com",
"timestamp": "1:30pm",
"datestampe": "25/01/2016"
},
{
"usernumber": "2",
"userid": "jasmeet",
"userpassword": "password",
"useremail": "jasmeet#nagarro.com",
"timestamp": "1:30pm",
"datestampe": "25/01/2016"
},
{
"usernumber": "3",
"userid": "manoj30dec",
"userpassword": "password",
"useremail": "manoj.kumar#nagarro.com",
"timestamp": "1:30pm",
"datestampe": "25/01/2016"
},
{
"usernumber": "4",
"userid": "lavish",
"userpassword": "password",
"useremail": "lavish.sharma#nagarro.com",
"timestamp": "1:30pm",
"datestampe": "25/01/2016"
}
]}
$http.get('data.json'). //json file path
success(function(data, status, headers, config) {
alert("Success");
$scope.resutls = data;
}).
error(function(data, status, headers, config) {
alert("Error");
// log error
});
Similar question I have answered here
Http get json file data and display
At last loop through the result and get the data/user which you need.
You don't tell on which creatirea you want to filter the user.
warning! The success and error for $http are depreciated, use then instead!
Deprecation Notice
The $http legacy promise methods success and error have been
deprecated. Use the standard then method instead. If
$httpProvider.useLegacyPromiseExtensions is set to false then these
methods will throw $http/legacy error.
// i will update this function when you provide more details
var getData = function(users){
for(var i in users{
if(users[i]["theFieldYouWant"] == theValueYouWant){
return users[i];
}
}
}
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
$scope.results = getData(response);
},
function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
}
);
you can use like this
$http.get('data.json').then(function(response) {
console.log(response);
$scope.results = response;
},
function(error) {
$scope.results = [];
console.log(error);
});
success and error methods are deprecated.
You can use 'then' instead
$http.get('data/registered-user-list.json').then(function(response) {
if (response.status == 200) {
$scope.results = data;
} else {
// log error
}
});
I'm new to JavaScript and AngularJS. I'm tryin' to build up a very simple CRUD application. Here is the code of my controller:
(function() {
var app = angular.module('form.user', []);
app.directive('formusergui', [function(){
return {
restrict: 'E',
templateUrl: './js/views/user.form.html',
controller: function($scope, $http) {
this.formToBean = function() {
var ent = {};
ent.id = null;
ent.name = $scope.name;
ent.desc = $scope.desc;
ent.reg = Date.now;
ent.linkImgProfile = null;
ent.type = null;
return ent;
};
this.create = function() {
$http.post('./services/users', JSON.stringify(this.formToBean()))
.success(function(data, status, headers, config) {
$scope.esito = "success: " + JSON.stringify(data);
})
.error(function(data, status, headers, config) {
$scope.esito = "error: " + JSON.stringify(data);
});
};
this.delete = function() {
$http.delete('./services/users', JSON.stringify(this.formToBean()))
.success(function(data, status, headers, config) {
$scope.esito = "success: " + JSON.stringify(data);
})
.error(function(data, status, headers, config) {
$scope.esito = "error: " + JSON.stringify(data);
});
};
...
},
controllerAs: 'userForm'
};
}]);
})();
formToBean function collects data by the form. As the create function works well (REST service is called), the delete function broke with this error:
TypeError: Cannot assign to read only property 'method' of {"id":null,"name":"john","desc":"doe","linkImgProfile":null,"type":null}
I found similar questions about this kind of error but still I can't get what's going wrong.
for the delete method in the $http, the second parameter is a configuration, in your request instead of configuration related data, simple the json object is passed, refer the api for the $http.delete
https://docs.angularjs.org/api/ng/service/$http#delete
$http.delete('./services/users/:idtodelete')
.success(function(data, status, headers, config) {
$scope.esito = "success: " + JSON.stringify(data);
});
I'm trying to create a live search function with AngularJS. I got a input field:
<input type="text" placeholder="Search" data-ng-model="title" class="search">
it there away to pass the search keyword inside the scope so i can perform a live search (JS) and display the results directly to the DOM
var app = angular.module("DB", []);
app.controller("Controller", function($scope, $http) {
$scope.details = [],
$http.defaults.headers.common["Accept"] = "application/json";
$http.get('http://api.org/search?query=<need to pass search name here>&api_key=').
success(function(data, status, headers, config) {
}).
error(function(data, status, headers, config) {
//handle errors
});
});
Inside the angular controller use a watch expression.
$scope.$watch('title', function (newValue, oldValue) {
if(newValue != oldValue) {
$http.get('http://api.org/search?query=' + newValue + '&api_key=')
.success(function(data, status, headers, config) { /* Your Code */ })
.error(function(data, status, headers, config) { /* Your Code */ });
}
});
You can use watch as #Justin John proposed, or can use ng-change
when using ng-change your controller should look something like this
app.controller("Controller", function($scope, $http) {
$http.defaults.headers.common["Accept"] = "application/json"; //should be moved to run block of your app
$scope.details = [];
$scope.search= function() {
$http.get("http://api.org/search?query="+$scope.title+"&api_key=")
.success(function(data, status, headers, config) { .... })
.error(function(data, status, headers, config) {//handle errors });
}
});
and your html
<input type="text" placeholder="Search" data-ng-model="title" class="search" data-ng-change="search()">
<input type="text" placeholder="Search" data-ng-model="title" class="search" data-ng-change="search()">
app.controller("Controller", function($scope, $http) {
$scope.details = [],
$scope.search= function() {
var url = "http://api.org/search?query="+$scope.title+"&api_key=";
$http.defaults.headers.common["Accept"] = "application/json";
$http.get(url).
success(function(data, status, headers, config) {
}).
error(function(data, status, headers, config) {
//handle errors
});
};
});