Angular $http service not getting objects from .JSON file - angularjs

Here is my http service code:
app.controller('StoreController', ['$http', function($http){
var store = this;
store.products = [];
$http.get('/store-products.json').then(function(data){
store.products = data;
});
}]);
And here is my JSON code:
[
{
"name": "...",
"price": 20.00,
"description": "...",
"canPurchase": false,
"images": [
"...jpg",
"...jpg",
"...jpg"
],
"reviews": []
},
{
"name": "...",
"price": 15.95,
"description": "...",
"canPurchase": true,
"images": [],
"reviews": []
}
]
When I run the code on localhost server, it does not show my objects. There is also no errors in the console that show so I cannot see where I am going wrong. Can anyone see the issue here?

your json data is wrapped at response.data of $http.get.
change to below code will solve the problem(also make sure your json file is at right location).
$http.get('/store-products.json').then(function(res){
store.products = res.data;
});
Plunker demo.

Related

add new data to json with angular js

Hello I am using angular js. Ii try to delete data from my json but when I refresh the page the json file still didn't change. The data I have deleted still there.
I put my json on myjson.com
[
{
"id":1,
"name": "sarah",
]
},
{
"id":2,
"name": "tommy"
]
}
{
"id":2,
"name": "rian"
]
}
]
This is my code for delete the data:
$scope.deleteItem =function(experience){
var index = $scope.experiences.indexOf(experience);
alert("Deleting DATA: "+ index);
$scope.experiences.splice(index,1);
};
Do I need to code php or something? I thought I can delete the file with just code from angularjs. I'm still new here so please can you tell me.

AngularJS deferred $http.get response, empty array

Please help in changing this code to be able to use $http.get html, at the moment the resulting array (html_controls) is empty. However, I can see the response in the console for all the request in $http.get. Thank you.
angular.module('exodus-grid').controller('DynamicPropertiesController', ['$scope', '$http', '$templateCache', '$q', 'coreFactory',
function($scope, $http, $templateCache, $q, coreFactory) {
//$scope.DynamicProperties = 'Property being added to the controller.';
//coreFactory.fetchData('http://uat.resources.newscdn.com.au/cs/networksales/products/latest/products.json', 'products');
// TODO: Change this harcoded value to the products.json in s3
$scope.products = [{
"id": "btyb",
"label": "BTYB + Superskin",
"description": "",
"name": "btyb",
"active": true,
"properties": [{
"bannerLink": [{
"tmp_prop_name": "bannerLink",
"label": "Header Tracking Link (Desktop)",
"type": "textbox"
}],
"superskinLink": [{
"tmp_prop_name": "superskinLink",
"label": "Sideskin Tracking Link (Desktop)",
"type": "textbox"
}],
"ImgUrl": [{
"tmp_prop_name": "ImgUrl",
"label": "Header Image Url",
"type": "textbox"
}]
}]
}, {
"id": "iframe",
"label": "iframe",
"description": "",
"name": "iframe",
"active": true,
"properties": [{
"link": [{
"tmp_prop_name": "link",
"label": "iFrame source Url",
"type": "textbox"
}]
}]
}];
var requests = [];
var html_controls = [];
var product = $scope.products[0];
var properties = angular.fromJson(product.properties);
//console.log(angular.toJson(properties));
angular.forEach(properties, function(property) {
angular.forEach(property, function(item) {
//console.log(angular.toJson(property));
if (item[0].type === "textbox") {
//console.log(angular.toJson(item));
//console.log(Object.getOwnPropertyNames(property));
//console.log(Object.keys(property));
$http.get("plugins/k-plugin-exodus-grid/templates/properties/textbox.html").success(function(html) {
html = html.replace("%%label%%", item[0].label);
html = html.replace("%%scope%%", item[0].tmp_prop_name);
//console.log(html);
html_controls.push(html);
console.log(html_controls);
var deferred = $q.defer();
requests.push(deferred.promise);
console.log(deferred, deferred)
}).then(function() {
//$scope.html = html_controls;
});
}
});
});
//console.log(html_controls);
//$scope.html = html_controls;
$q.all(requests).then(function(data) {
console.log("12312312 " , data);
$scope.html = html_controls;
});
}
]);
Looks like you are trying to resolve a array of empty promises. Since it is running async, when $q.all() us called, requests[] is still empty.
Try building an array of promises and then resolve this using q.all() instead:
var requests = []; // a list of promises
angular.forEach(properties, function(property) {
angular.forEach(property, function(item) {
var promise = $http.get("/yoururl"); // $http.get returns a promise
requests.push(promise); // add to list of requests as a promise
});
});
$q.all(requests).then(function (result) {
console.log('results' + result);
});

$httpBackend .whenGet is not a function in Angular

I am trying to make a dummy service to get data in Angular, I am using ngMockE2E, and my code for the Mock looks like this:
(function () {
"use strict"
var app = angular
.module("productResourceMock", ["ngMockE2E"]);
app.run(function ($httpBackend) {
var products = [
{
"productId": 1,
"productName": "mobile1",
"productCode": "heh4",
"releaseDate": "May 21, 2013",
"description": "very nice mobile",
"cost": 200,
"price": 300,
"category": "Electronics",
"tags": ["mobile", "electronic"],
"imageUrl": "images/img1.jpg"
},
{
"productId": 2,
"productName": "mobile2",
"productCode": "heh4",
"releaseDate": "May 21, 2012",
"description": "not a nice mobile",
"cost": 100,
"price": 500,
"category": "Electronics",
"tags": ["mobile", "Electronic"],
"imageUrl": "images/img2.jpg"
}];
var productUrl = "/api/products";
$httpBackend.whenGet(productUrl).respond(products);
});
}());
I have defined my controller, and inside it, it has this code:
(function () {
"use strict"
angular
.module("productManagement")
.controller("ProductListCtrl",
["productResource",
ProductListCtrl]);
function ProductListCtrl(productResource) {
var vm = this;
productResource.query(function(data){
vm.products = data;
});
}
}());
And for my service that sends the REST requests, I have this code:
(function () {
"use strict"
angular
.module("common.services")
.factory("productResource",
["$resource", productResource]);
function productResource($resource) {
return $resource("/api/products/:productId");
}
}());
am still getting this error: Uncaught TypeError: $httpBackend.whenGet is not a function.
Any help is appreciated, or any clarification needed, please let me know.
Answer is simple: replace whenGet with whenGET
Be careful to write the http verb all in uppercase.
See ngMock documentation

Loopback, AngularJS and validation

I followed this tutorial to create a project with Loopback and AngularJs. https://github.com/strongloop/loopback-example-angular
Now, I have an application with:
HTML files (with Bootstrap)
AngularJS controllers
AngularJS service (generated with syntax lb-ng server/server.js client/js/services/lb-services.js)
Model (located in ./common folder)
MongoDB backend
The model "Device" is defined in ./common/models/device.js
module.exports = function(Device) {
};
And in ./common/models/device.json
{
"name": "Device",
"base": "PersistedModel",
"idInjection": true,
"properties": {
"name": {
"type": "string",
"required": true
},
"description": {
"type": "string",
"required": true
},
"category": {
"type": "string",
"required": true
},
"initialDate": {
"type": "date"
},
"initialPrice": {
"type": "number",
"required": true
},
"memory": {
"type": "number"
}
},
"validations": [],
"relations": {},
"acls": [],
"methods": []
}
In the "AddDeviceController", I have an initialization part with:
$scope.device = new DeviceToBuy({
name: '',
description: '',
category: '',
initialPrice: 0,
memory: 8
initialDate: Date.now()
});
And I am able to save the $scope.device when executing the following method:
$scope.save = function() {
Device.create($scope.device)
.$promise
.then(function() {
console.log("saved");
$scope.back(); // goto previous page
}, function (error) {
console.log(JSON.stringify(error));
});
}
When everything is valid, the model is saved in the backend. If something is not valid in the $scope.device, I receive an error from my backend. So everything is working fine.
Now, I would like to use the model to perform client-side validation before sending my model to the backend and put some "error-class" on the bootstrap controls.
I tried something in the $scope.save function before sending to the backend:
if ($scope.device.isValid()) {
console.log("IsValid");
} else {
console.log("Not Valid");
}
But I get an exception "undefined is not a function" --> isValid() doesn't exist.
And I cannot find any example on how to execute this client-side validation.
LoopBack models are unopinionated and therefore do not provide client side validation out-of-box. You should use Angular validation mechanisms before calling $save.

Why is my $watch showing an array that appears to be empty?

I'm working on creating an AngularJS directive in order to use D3 to render a visualization, but I'm running into problems when it comes to setting a $watch. The majority of my stuff looks extremely similar to the AngularJS tutorial. My resources are configured in a file called resources.json, which I'm sure is returning correctly.
Here's the relevant code of what I have so far:
app.js
var resourceApp = angular.module("resourceApp", [
'ngRoute',
'resourceControllers',
'resourceDirectives',
'resourceServices'
]);
/* ... routing config ... */
controllers.js
var resourceControllers = angular.module('resourceControllers', []);
resourceControllers.controller("OverviewCtrl", [ '$scope', 'Resource',
function($scope, Resource) {
$scope.resources = Resource.query();
}
]);
/* ... other controllers ... */
directives.js
var resourceDirectives = angular.module('resourceDirectives', []);
resourceDirectives.directive("resourceVisualization", function() {
return {
restrict: 'E',
scope: {
resources: '='
},
link: function(scope, el, attrs) {
// svg setup is here
scope.$watch("resources", function(nRes, oRes) {
if (nRes) {
// this logs an array of Resource objects
//(once expanded in Firebug)
console.log(nRes);
var cats = nRes.map(function(r) { return r.category; });
// this logs an empty array
console.log(cats);
}
});
}
};
});
overview.html
<ul>
<li ng-repeat="resource in resources">
{{resource.name}}
</li>
</ul>
<resource-visualization resources="resources"></resource-visualization>
resources.json (which is what services.js is configured to pull from)
[
{
"id": 1,
"category": "test",
"type": "sample",
"name": "Test1"
},
{
"id": 2,
"category": "test",
"type": "sample4",
"name": "Test2"
},
{
"id": 3,
"category": "fake",
"type": "sample1",
"name": "Test3"
},
{
"id": 4,
"category": "new",
"type": "sample2",
"name": "Test4"
}]
Now, I know that the REST call is working, because the <ul> is populated. However, in the directive, the logging statements are returning empty arrays. I'm aware of the the async-ness of $resource, but the object that is logged first in the $watch contains $resolved: true.
Am I missing something?
It's all fine. Your call to Resource.query() returns immediately an empty array. If the ajax call returns the real data, your array will be filled with the arrived data. So the first assignment to $scope.resources fires your $watch function with an empty array. You my solve your problem if you are using the $watchCollection function. See http://docs.angularjs.org/api/ng.$rootScope.Scope for further information.

Resources