How should i access URL json array data using angular.forEace.
i am trying to get data but giving some error please check below code i have added
[{
"flightsDepartur":[
{
"fare":"9,000",
"route":[
{
"source":"Delhi",
}
],
},
]
}]
$http.get('data.json').then(function(response) {
$scope.allData = response;
},function(dataStatus){
console.log(dataStatus);
});
angular.forEach($scope.allData, function(flidata) {
angular.forEach(flidata[0].flightsDepartur, function(flidatIn) {
console.log(flidatIn.fare);
});
});
check the below to get fare and route data
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = [{
"flightsDepartur":[
{
"fare":"9,000",
"route":[
{
"source":"Delhi",
}
],
},
]
}];
angular.forEach($scope.name, function(k,v) {
angular.forEach(k, function(k,v) {
console.log(k[0].fare);
console.log(k[0].route[0].source)
});
});
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
</body>
</html>
The problem is you are assigning values to $scope.allData inside a promise. since the javascript asynchronous before the data being assign to $scope.allData for each loop start to execute. at that time $scope.allData was undefined. so it produces an error.
create a function and call that inside the promise to prevent the error
$http.get('data.json').then(function(response) {
$scope.allData = response.data;
callLoop()
},function(dataStatus){
console.log(dataStatus);
});
function callLoop(){
angular.forEach($scope.allData, function(flidata) {
angular.forEach(flidata.flightsDepartur, function(flidatIn) {
console.log(flidatIn.fare);
});
});
}
Try change
angular.forEach(flidata[0].flightsDepartur, function(flidatIn) {..
to
angular.forEach(flidata.flightsDepartur, function(flidatIn) {..
and when using then function to get response change to this.
$http.get('data.json').then(function(response) {
$scope.allData = response.data;
},function(dataStatus){
console.log(dataStatus);
});
Demo
var app = angular.module('anApp', []);
app.controller('ctrl', function($scope) {
$scope.allData = [{
"flightsDepartur": [{
"fare": "9,000",
"route": [{
"source": "Delhi",
}],
}, ]
}]
angular.forEach($scope.allData, function(flidata) {
angular.forEach(flidata.flightsDepartur, function(flidatIn) {
console.log(flidatIn.fare);
console.log(flidatIn.route[0].source);
});
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.min.js"></script>
<div ng-app="anApp" ng-controller="ctrl">
</div>
Related
Hi i wondering that ploblem so i want ask somebody
so please give me solution?
I make html file like that photo
but when i open this html file this file not working…
any data not diplay
what is the ploblem in this html file?enter image description here
<!doctype html>
<html ng-app="myApp">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<div ng-controller="QueryController">
</div>
<script src="node_modules/angular/angular.js"></script>
<script src="node_modules/elasticsearch-browser/elasticsearch.angular.js"></script>
<script>
var myApp = angular.module('myApp', ['elasticsearch']);
// Create the es service from the esFactory
myApp.service('es', function (esFactory) {
return esFactory({ host: 'localhost:9200'});
});
myApp.controller('ServerHealthController', function($scope, es, esFactory) {
es.cluster.health(function (err, resp) {
if (err) {
$scope.data = err.message;
} else {
$scope.data = resp;
}
});
});
// We define an Angular controller that returns query results,
// Inputs: $scope and the 'es' service
myApp.controller('QueryController', function($scope, es, esFactory) {
// search for documents
es.search({
index: 'epowersyst',
type: 'logs',
body: {
query:
{
match_all : {} }
}
}).then(function (response) {
$scope.hits = response;
console.log($scope.hits)
alert("hits값 : " + response);
});
});
</script>
</body>
</html>
My application is executed successfully without maninSvc.js. After adding this file I'm seeing errror:
angular.min.js:123 Error: [$controller:ctrlreg] http://errors.angularjs.org/1.6.5/$controller/ctrlreg?p0=MainController
at angular.min.js:7
My Code:
Index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<title></title>
<script src="Scripts/jquery-3.2.1.min.js"></script>
<script src="Scripts/bootstrap-3.3.7/js/bootstrap.min.js"></script>
<script src="Scripts/angular.min.js"></script>
<script src="Scripts/angular-route.min.js"></script>
<script src="Scripts/angular-resource.min.js"></script>
<link href="Scripts/bootstrap-3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<link href="Css/Shared.css" rel="stylesheet" />
<script src="MainController.js"></script>
<script src="mainSvc.js"></script>
</head>
<body ng-controller="MainController as vm">
<div data-ng-if="vm.success" class="success">{{vm.success}}</div>
<div data-ng-if="vm.catch" class="catch">{{vm.catch}}</div>
<div data-ng-if="vm.finally" class="finally">{{vm.finally}}</div>
</body>
</html>
MainController.js
(function() {
angular
.module('app', ['ngRoute'])
.controller('MainController', mainController);
mainController.$inject = ['mainSvc'];
function mainController(mainSvc) {
var vm = this;
mainSvc.getData()
.then(function(data) {
vm.success = "success";
}).catch(function(response) {
vm.catch = "catch";
}).finally(function() {
vm.finally = "finally";
});
}
})();
mainSvc.js
(function() {
angular
.module('app', [])
.factory('mainSvc', mainSvc);
mainSvc.$inject = ['$resource'];
function mainSvc($resource) {
var ResourceData = $resource({
query: {
isArray: true
},
get: {},
save: {
method: 'POST'
},
update: {
method: 'PATCH'
},
put: {
method: 'PUT'
},
remove: {
method: 'DELETE'
}
});
return {
getData: getData,
};
function getData() {
/// <summary>
/// Gets Data
/// </summary>
return ResourceData
.get()
.$promise;
}
}
})();
Your mainSvc.js should not have empty dependencies to the module, Then it will be considered as a new module. change it as
(function () {
angular
.module('app')
.factory('mainSvc', mainSvc);
I have a function below that works fine and passes info into and retrieves from a cookieStore without issue
$scope.num = 0
$scope.nums = []
$scope.increment = function () {
$scope.num++
}
$scope.$watch('num', function () {
$scope.nums.push($scope.num)
})
$scope.storeProductsInCookie=function(){
$cookieStore.put("invoices",$scope.nums)
};
$scope.getProductsInCookie=function(){
console.log( $cookieStore.get("invoices",$scope.nums));
}
However when I try with the below verufyGuess function that is injecting the Index and no as parameters into the function it fails to place into the cookieStore
$scope.verifyGuess = function (Index , no) {
$scope.votes = {};
$scope.newVotes = []
$scope.votes[Index] = $scope.votes[Index] || 0;
$scope.votes[Index]+= no;
$scope.$watch('votes', function () {
$scope.newVotes.push($scope.votes)
})
$scope.storeProductsInCookie=function(){
$cookieStore.put("invoices",$scope.newVotes)
};
$scope.getProductsInCookie=function(){
console.log( $cookieStore.get("invoices",$scope.newVotes));
}
$cookieStore is Deprecated: (since v1.4.0)
Please use the $cookies service instead.
$scope.nums is an array of strings.So $cookieStore is storing them as string(cookies only support strings to store).
In second case $scope.newVotes is an array of objects. cookies wont store objects.
you must use $cookieStore.put("invoices", JSON.stringify($scope.newVotes))
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.12/angular-cookies.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<script>
var app = angular.module('plunker', ['ngCookies']);
app.controller('MainCtrl', function($scope, $cookies) {
$scope.votes = {};
$scope.newVotes = []
var Index = 0;
$scope.votes[Index] = $scope.votes[Index] || 0;
$scope.votes[Index] += 10;
$scope.newVotes.push($scope.votes)
$scope.storeProductsInCookie = function() {
$cookies.put("invoices", JSON.stringify($scope.newVotes))
};
$scope.getProductsInCookie = function() {
console.log($cookies.get("invoices"));
}
$scope.storeProductsInCookie();
$scope.getProductsInCookie();
});
</script>
</body>
</html>
I have object like this i need to get "GetToolInfo" name:
{"GetToolInfo":{
"Item":[
{
"_Key":"DefaultPath",
"_Value":"C:\\Users\\vkedarix\\Desktop\\TAT\\Host\\DefaultWorkSpace.xml"
},{
"_Key":"IsLicenseAgreed",
"_Value":"1"
}
]
}
}
Hi, This sample show to you how can get keys from object:
var app = angular.module("app", []);
app.controller("ctrl", function ($scope, $filter) {
var foo = {
"GetToolInfo": {
"Item": [
{
"_Key": "DefaultPath",
"_Value": "C:\\Users\\vkedarix\\Desktop\\TAT\\Host\\DefaultWorkSpace.xml"
}, {
"_Key": "IsLicenseAgreed",
"_Value": "1"
}
]
}
};
for (var key in foo) {
console.log(key);
$scope.key = key
}
});
<!doctype html>
<html ng-app="app" ng-controller="ctrl">
<head>
</head>
<body>
{{key}}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</body>
</html>
In this example, I have an e2e test doing a button click, which executes a function that does a POST
I would like to be able to have access to the "data" object from testDev httpBackend callback, in my e2e scenerios code, for verification.
Is this possible in an e2e test? If so, could you point me in the right direction?
thanks
scenerio code
describe('test2 app', function() {
beforeEach(function() {
browser().navigateTo('/testbed/e2e/app/index2.html');
});
it('should run a POST',function() {
element('#myButton2').click();
});
});
test module
var test2Dev = angular.module('test2Dev', ['test2App', 'ngMockE2E'])
.run(function($httpBackend) {
$httpBackend.whenPOST(/testpost/)
.respond(function(method, url, data, headers){
console.log(data);
return [200, data, {}];
});
});
markup
<html lang="en" ng-app="test2Dev" ng-controller="test2Ctrl">
<head>
<meta charset="utf-8">
<title>Test click </title>
<link rel="stylesheet" href="css/app.css">
<link rel="stylesheet" href="css/bootstrap.css">
<script src="lib/angular/angular.js"></script>
<script src="lib/angular/angular-mocks.js"></script>
<script src="/testbed/e2e/test/e2e/test2Dev.js"></script>
<script src="js/controllers2.js"></script>
</head>
<body>
<button id="myButton2" ng-click="runPost()">run post</button>
</body>
</html>
controller
var test2App = angular.module('test2App', []);
test2App.controller('test2Ctrl', function($scope,$http) {
$scope.runPost = function() {
$http.post('/testpost',{
data1 : 'chevy',
data2 : 'ford'
});
}
});
runner
<!doctype html>
<html lang="en">
<head>
<title>End2end Test Runner</title>
<meta charset="utf-8">
<base href="../..">
<script src="app/lib/angular/angular-scenario.js" ng-autotest></script>
<script src="app/lib/angular/angular-mocks.js" ng-autotest></script>
<script src="/testbed/e2e/test/e2e/test2Dev.js"></script>
<script src="/testbed/e2e/test/e2e/scenarios2.js"></script>
</head>
<body>
</body>
</html>
Not very pretty but I removed my test module, and used a changed version of "mockApi" here->
https://github.com/blabno/ngMockE2E-sample (thank you Bernard Labno)
changed e2e.mocks.js to add the data object to it's config obj->
function setup(method, url, config)
{
$httpBackend.when(method, url).respond(function (requestMethod, requestUrl, data, headers) {
config.triggered = true;
config.data = data;
var response = config.response || {};
if (config.serverLogic) {
response = config.serverLogic(requestMethod, requestUrl, data, headers);
}
return [response.code || 200, response.data];
});
}
setup(POST, /testpost/, mocks.api.post_test);
.... and added this method to access it....
chain.getData = function() {
return this.addFuture("get data object for " + itemName, function(done) {
done(null,JSON.parse(api[itemName].data));
});
};
... here is my scenerio now...
it('should run a POST',function() {
element('#myButton2').click();
expect(mockApi("post_test").getData()).toEqual({
data1 : 'chevy',
data2 : 'ford'
});
});
Is there a better way to do this?