Get first key name from object angular js? - angularjs

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>

Related

Access json data using angular.forEach

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>

Data is showing in controller and service but not showing in view

view--index.html it will print array of data in ng-repeat
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>hii</title>
<script src="bower_components/angular/angular.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<h1>wellcom </h1>
<p ng-repeat="d in data1 track by $index">{{d}}</p>
<!--<h3 ng-repeat="d1 in data2"> Type Of data are: {{d1}}</h3>-->
</body>
<script src="controller.js">
</script>
<script src="service.js">
</script>
</html>
This is my service, where I set some data type to Redis server and I retrieve that data type and return data to controller.
var Promise = require("bluebird");
var redis = Promise.promisifyAll(require("redis"));
var client = redis.createClient();
angular.module('myApp')
.service('redisService', function ($q) {
this.getAll = function () {
var a1 = [];
return $q(function (resolve, reject) {
// client.set("string key", "string val", redis.print);
// client.hset("hash name", "hashkey 1", "some value", redis.print);
// client.hset("hash name", "hashkey 2", "some other value", redis.print);
// client.lpush("mylist", "In", redis.print);
client.scanAsync(0).then(function (data) {
data[1].forEach(function (reply) {
client.typeAsync(reply).then(function (a) {
a1.push(a);
})
})
});
return resolve(a1);
})
}
});
This is my controller in this data is coming and printing to console but data is not setting to view i.e not showing to index.html
angular.module('myApp', [])
.controller('myCtrl', function ($scope, redisService, $q) {
$scope.data1;
redisService.getAll().then(function (data) {
$scope.data1 = data;
console.log('data is', $scope.data1)
})
})

AngularJS filter array of objects, including nested array, with value from <input>

I have such array of objects:
var cars = [
{
"carMake":"Audi",
"models":[
"A4",
"A6",
"R8"
]
},
{
"carMake":"BMW",
"models":[
"3er",
"X3",
"i8",
"7er"
]
},
{
"carMake":"Toyota",
"models":[
"Corolla",
"Auris",
"Yaris",
"Gt86",
"Rav4"
]
}
];
And I have tried below AngularJS code for searching:
$scope.searching = '';
$scope.producers = [];
$scope.models = [];
$scope.searchCar = function() {
$scope.producers = $filter('filter')(cars, function(value) {
return value.carMake === $scope.searching;
});
$scope.models = $filter('filter')(cars, function(value) {
return angular.forEach(value.models, function(model) {
return model === $scope.searching;
});
});
};
Inside HTML I have:
<label>What do you want to find?
<input type="text" ng-model="searching" ng-change="searchCar()" placeholder="Search...">
</label>
<ul>
<li ng-repeat="producer in producers">{{producer}}</li>
</ul>
<ul>
<li ng-repeat="model in models">{{model}}</li>
</ul>
My code doesn't work as I expected - it only outputs whole cars Array element. For example, when I type "Audi" i got whole "Audi object", although I want separately results for car producers and/or car models that match pattern inside <input>.
I want searching to work like, when I type "Au" then I will see "Audi" in first list and "Auris" in the second. So searching should work as well for cars.carMake as for cars.models[] and present result in both lists (first/left for car producers and second/right for car models).
I'd suggest you to store the items in separated arrays, then use the filter in view:
(function() {
angular
.module("app", [])
.controller('MainCtrl', MainCtrl);
MainCtrl.$inject = ['$scope'];
function MainCtrl($scope) {
$scope.sensitiveCompare = sensitiveCompare;
var cars = [
{
"carMake":"Audi",
"models":[
"A4",
"A6",
"R8"
]
},
{
"carMake":"BMW",
"models":[
"3er",
"X3",
"i8",
"7er"
]
},
{
"carMake":"Toyota",
"models":[
"Corolla",
"Auris",
"Yaris",
"Gt86",
"Rav4"
]
}
];
$scope.producers = cars.map(function(car) {
return car.carMake;
});
$scope.models = [];
cars.forEach(function(car) {
$scope.models = $scope.models.concat(car.models);
});
function sensitiveCompare(input, search) {
return ('' + input).indexOf('' + search) > -1;
}
}
})();
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
</head>
<body ng-controller="MainCtrl">
<label>What do you want to find?
<input type="text" ng-model="searching" ng-change="searchCar()" placeholder="Search...">
</label>
<ul>
<li ng-repeat="producer in producers | filter: searching: sensitiveCompare" ng-bind="producer"></li>
</ul>
<ul>
<li ng-repeat="model in models | filter: searching: sensitiveCompare" ng-bind="model"></li>
</ul>
</body>
</html>
EDIT:
If you really want to create your custom function for this, check this:
(function() {
angular
.module("app", [])
.controller('MainCtrl', MainCtrl);
MainCtrl.$inject = ['$scope', '$filter'];
function MainCtrl($scope, $filter) {
$scope.searchCar = searchCar;
var cars = [
{
"carMake":"Audi",
"models":[
"A4",
"A6",
"R8"
]
},
{
"carMake":"BMW",
"models":[
"3er",
"X3",
"i8",
"7er"
]
},
{
"carMake":"Toyota",
"models":[
"Corolla",
"Auris",
"Yaris",
"Gt86",
"Rav4"
]
}
];
$scope.producers = [];
$scope.models = [];
function searchCar() {
$scope.producers = $filter('filter')(cars, function(car) {
return car.carMake.indexOf($scope.searching) !== -1;
});
$filter('filter')(cars, function(car) {
$scope.models = car.models.filter(function(model) {
return model.indexOf($scope.searching) !== -1;
})
});
}
}
})();
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body ng-controller="MainCtrl">
<label>What do you want to find?
<input type="text" ng-model="searching" ng-change="searchCar()" placeholder="Search...">
</label>
<ul>
<li ng-repeat="producer in producers" ng-bind="producer.carMake"></li>
</ul>
<ul>
<li ng-repeat="model in models" ng-bind="model"></li>
</ul>
</body>
</html>

How to display Ui-grid after data getting from services?

This is my code
var app = angular.module('app', ['ngTouch', 'ui.grid']);
app.controller('MainCtrl', ['$scope', '$http', function ($scope, $http) {
var today = new Date();
$scope.gridOptions = {
enableFiltering: false,
onRegisterApi: function(gridApi){
$scope.gridApi = gridApi;
$scope.gridApi.grid.registerRowsProcessor( $scope.singleFilter, 200 );
},
columnDefs: [
{ field: 'name' },
{ field: 'gender', cellFilter: 'mapGender' },
{ field: 'company' },
{ field: 'email' },
{ field: 'phone' },
{ field: 'age' },
{ field: 'mixedDate' }
]
};
$http.get('https://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/data/500_complex.json')
.success(function(data) {
$scope.gridOptions.data = data;
$scope.gridOptions.data[0].age = -5;
data.forEach( function addDates( row, index ){
row.mixedDate = new Date();
row.mixedDate.setDate(today.getDate() + ( index % 14 ) );
row.gender = row.gender==='male' ? '1' : '2';
});
});
$scope.filter = function() {
$scope.gridApi.grid.refresh();
};
$scope.singleFilter = function( renderableRows ){
var matcher = new RegExp($scope.filterValue);
renderableRows.forEach( function( row ) {
var match = false;
[ 'name', 'company', 'email' ].forEach(function( field ){
if ( row.entity[field].match(matcher) ){
match = true;
}
});
if ( !match ){
row.visible = false;
}
});
return renderableRows;
};
}])
.filter('mapGender', function() {
var genderHash = {
1: 'male',
2: 'female'
};
return function(input) {
if (!input){
return '';
} else {
return genderHash[input];
}
};
});
<!doctype html>
<html ng-app="app">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular-touch.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular-animate.js"></script>
<script src="http://ui-grid.info/docs/grunt-scripts/csv.js"></script>
<script src="http://ui-grid.info/docs/grunt-scripts/pdfmake.js"></script>
<script src="http://ui-grid.info/docs/grunt-scripts/vfs_fonts.js"></script>
<script src="http://ui-grid.info/release/ui-grid.js"></script>
<link rel="stylesheet" href="http://ui-grid.info/release/ui-grid.css" type="text/css">
<link rel="stylesheet" href="main.css" type="text/css">
</head>
<body>
<div ng-controller="MainCtrl">
<input ng-model='filterValue'/><button ng-click='filter()'>Filter</button>
<div id="grid1" ui-grid="gridOptions" class="grid"></div>
</div>
<script src="app.js"></script>
</body>
</html>
In the above code first ui-grid structure display then after data will bind to the ui-grid, but i want to display entire grid with structure after loading data.
this is my plunker http://plnkr.co/edit/?p=preview
A popular design is to show loading status when data is not yet loaded, to do so, you could add a dataLoaded flag to control when the grid is ready, set the flag as true in the success callback of $http.get. See the below:
$scope.dataLoaded = false;
$http.get('https://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/data/500_complex.json').success(function(data) {
// ...
$scope.dataLoaded = true;
});
and in your template, it could be as:
<div id="grid1" ui-grid="gridOptions" class="grid" ng-show="dataLoaded"></div>
<div ng-hide="dataLoaded">Loading...</div>

I can not get the select working correctly in angularjs

I tried to do as this article recommends to get select-options working in AngularJS.
http://gurustop.net/blog/2014/01/28/common-problems-and-solutions-when-using-select-elements-with-angular-js-ng-options-initial-selection/
However I have got it messed up some how. Here is a fiddlerjs of the code
http://jsfiddle.net/8faa5/
Here is the HTML
<!DOCTYPE html>
<html class="no-js" data-ng-app="TestModule">
<head>
<title></title>
</head>
<body data-ng-controller="TestController">
<h3>Test Select</h3>
Current Value: {{ ourData.CurrentSelected}} <br>
<select ng-init="ourData._currVal = {Value: ourData.CurrentSelected}"
ng-change="ourData.CurrentSelected = ourData._currVal.Value"
ng-model="ourData._currVal"
ng-options="oneItem.Value as oneItem.Disp
for oneItem in ourData.StuffForDropDown track by oneItem.Value"></select>
<!-- Get Javascript -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.18/angular.min.js"></script>
<script src="js/data.js"></script>
</body>
</html>
Here is js/data.js
(function() {
"use strict";
var smallData = {
StuffForDropDown: [
{
Disp: "01-Prospect",
Value: 5
},
{
Disp: "02-Constituet Issue",
Value: 10
}
],
CurrentSelected: "10"
};
var myModule = angular.module("TestModule", ['ui.mask']);
myModule.controller("TestController", ["$scope",
function ($scope){
$scope.ourData = smallData;
}
]);
})();
First of all, your jsfiddle is messed up. You have defined angularjs twice, once in the jsfiddle options and the second time in the code. Also you overcomplicated your code. I made a simple rewrite of your code that is working in this jsfiddle.
<div data-ng-app="TestModule">
<div data-ng-controller="TestController">
<h3>Test Select</h3>
Current Value: {{ ourData._currval}}
<br>
<select ng-init="ourData._currVal = {Value: ourData.CurrentSelected}"
ng-model="ourData._currval" ng-options="oneItem.Value as oneItem.Disp
for oneItem in ourData.StuffForDropDown"></select>
</div>
</div>
(function () {
"use strict";
var smallData = {
StuffForDropDown: [{
Disp: "01-Prospect",
Value: 5
}, {
Disp: "02-Constituet Issue",
Value: 10
}],
CurrentSelected: "10"
};
var myModule = angular.module("TestModule", []);
myModule.controller("TestController", ["$scope",
function ($scope) {
$scope.ourData = smallData;
}]);
})();
**Edit:
OK, I have revised my code according to your new request int the comment. The code goes as follows (new plunker)
<div data-ng-app="TestModule">
<div data-ng-controller="TestController">
<h3>Test Select</h3>
Current Value: {{ currentItem.Value}}
<br>
<select ng-model="currentItem" ng-options="u as u.Disp for u in items track by u.Value"></select>
</div>
</div>
(function () {
"use strict";
var myModule = angular.module("TestModule", []);
var ctrl = function ($scope) {
$scope.items = [{
Disp: "01-Prospect",
Value: 5
}, {
Disp: "02-Constituet Issue",
Value: 10
}];
$scope.currentItem = $scope.items[1];
};
myModule.controller("TestController", ctrl)
})();

Resources