I have a REST api from elasticsearch. I want to retrieve the data of a specific field. That is, I want to retrieve the data in the Gender field. What I have done is I have consume the rest service in AngularJS as follows. But nothing is appearing on the browser. Can somebody help to achieve what I want to display?
angular.module("view.index", ['ngRoute'])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/menuIndex/', {
templateUrl: 'view-index/template/index.html',
controller: 'NewController',
controllerAs: 'newCtrl',
});
}])
.controller('NewController', ['$timeout', 'overlayMessage', '$location', 'userInformation', '$http', '$scope','menuService', function ($timeout, overlayMessage, $location, userInformation, $http, $scope, menuService) {
var myCtrl = this;
myCtrl.Form = {};
$http.get('http://admin:admin#localhost:9200/index1/_search?_source=Gender').
success(function(data) {
myCtrl.json = data;
});
}]);
The GET api http://admin:admin#localhost:9200/index-data/_search?_source=Gender returns me a json body like this:
{
"took": 17,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 30003,
"max_score": 1,
"hits": [
{
"_index": "index1",
"_type": "tbl",
"_id": "1",
"_score": 1,
"_source": {
"Gender": "Female"
}
},
{
"_index": "index1",
"_type": "tbl",
"_id": "2",
"_score": 1,
"_source": {
"Gender": "Male"
}
}
And in my front end, I want to access the data in the Gender field like this:
<div ng-controller="menuNsmCtrl">
<div ng-repeat="json in json">
<p>The ID is {{json.Gender}}</p>
</div>
</div>
First use then instead of success to catch the data. success is deprecated since the angular version 1.4
$http.get('http://admin:admin#localhost:9200/index1/_search?_source=Gender').
then(function(response) {
myCtrl.json = response.data;
});
}]);
now since you use controllerAs syntax you need to use the reference variable in the html also
<div ng-controller="NewController as myCtrl">
<div ng-repeat="json in myCtrl.json.hits.hits">
<p>The ID is {{json['_source'].Gender}}</p>
</div>
</div>
Related
I have a main page displaying a list of houses and when I click on a particular house I want to display the house details. I am trying to achieve this using ui-view however, the house details are not showing.
These are my routes defined:
var app = angular.module('app', ['ui.router']);
app.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/about');
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'app/views/partial-home.html'
})
.state('about', {
url: '/about',
templateUrl: 'app/views/partial-about.html',
controller: 'inventoryCtrl'
})
.state('about.item', {
url: '/:id',
templateUrl: 'app/views/partial-about-item.html',
controller: 'detailsCtrl'
});
});
this is my main page html displaying a list of all houses:
<div ng-repeat="value in all | filter: (!!locationFilter || undefined) && {type: locationFilter} | filter: priceFilter | filter: datesFilter | orderBy:sortProp">
<ul>
<li><img src="app/images/{{value.image}}.jpg" alt="Smiley face" height="100" width="240"></li>
<li><strong>{{value.id}}</strong></li>
<li><strong>{{value.address}}</strong></li>
<li>city: {{value.city}}</li>
<li>postcode: {{value.postcode}}</li>
<li>price: £{{value.price}}</li>
<li>num_of_beds: {{value.num_of_beds}}</li>
<li>{{value.type}}</li>
<li>{{value.minutes}}</li>
<li>{{value.added}}</li>
</ul>
<a ng-href="#/about/{{value.address}}" class="btn btn-primary">View details</a>
</div>
<div ui-view></div>
this is my house details html displaying the house details which is only displaying the static text nothing inside ng-repeat or curly braces is shown
updated html:
<div>
<ul ng-repeat="item in singleHouse track by item.id">
<li>{{item.id}}</li>
<li>{{item.desc}}</li>
</ul>
</div>
this is my page details controller:
app.controller('detailsCtrl', ['$scope', 'DetailsFactory', '$stateParams', '$state', function($scope, DetailsFactory, $stateParams, $state) {
$scope.id = $stateParams.id;
DetailsFactory.getHouseDetails($stateParams.id).then(function(response){
$scope.singleHouse = response.detailsData.details;
console.log($scope.singleHouse);
})
}]);
I have added factory as well for the details house page:
app.factory('DetailsFactory', ['$http', '$stateParams', function($http, $stateParams) {
var urlBase = 'app/default/details.json';
var factory = {};
factory.getHouseDetails = function(id){
return $http.get(urlBase + id);
}
return factory;
}]);
and the json for the details page:
{
"detailsData":{
"details": [
{
"id": 1,
"desc": "Beautiful house blebel eble"
}, {
"id": 2,
"desc": "Beautiful house blebel eble"
}, {
"id": 3,
"desc": "Beautiful house blebel eble"
}, {
"id": 4,
"desc": "Beautiful house blebel eble"
}, {
"id": 5,
"desc": "Beautiful house blebel eble"
}, {
"id": 6,
"desc": "Beautiful house blebel eble"
}, {
"id": 7,
"desc": "Beautiful house blebel eble"
}, {
"id": 8,
"desc": "Beautiful house blebel eble"
}, {
"id": 9,
"desc": "Beautiful house blebel eble"
}, {
"id": 10,
"desc": "Beautiful house blebel eble"
}, {
"id": 11,
"desc": "Beautiful house blebel eble"
}, {
"id": 12,
"desc": "Beautiful house blebel eble"
}]
}
}
$stateParams.item just gives id. In your details controller you should get the house detail from server
app.controller('detailsCtrl', ['$scope', 'InventoryFactory', '$stateParams', '$state', function($scope, InventoryFactory, $stateParams, $state) {
InventoryFactory.getHouseDetail($stateParams.item).then(function(response){
$scope.singleHouse = response.data;
})
}]);
In your html
<ul ng-repeat="item in singleHouse">
<li>{{item.id}}</li>
<li>{{item.desc}}</li>
</ul>
Your ng-href="#/about/{{value.address}}" doesn't match up with your state declaration url: '/:item', it should be url: 'about/:item',
Hi friend I'm beginner in angular and getting stuck by using angular.forEach() function. I just want to call data from a nested array in data.json file. Please check my code below... ****I want to call data from --users-- key****
HTML
<div class="user-container" ng-controller="users">
<ul class="list">
<li ng-repeat="(key, value) in items">
{{key}} <p> {{value}}
</li>
</ul>
</div>
Problems with current code
When run my code in browser Its giving me only 2 <li> in ng-repeat then in {{Key}} I'm getting 0 in first <li> and 1 in second <li>
and in {{value}} I'm getting whole user list in first <li> and in second <li> their is no data
data.json
{
"data": {
"new": true,
"show_page": false,
"status": "signedin",
"users": [{
"Michele": {
"logo": "xyz.jpg",
"status": "active",
"active_since": 2015,
"order": 1
},
"Gerry": {
"logo": "xyz.jpg",
"status": "active",
"active_since": 2015,
"order": 1
}
}]
},
"success": true
}
Controller.js
var myApp = angular.module('app', []);
myApp.service('userData', ['$http', function($http){
return{
userslist : function(){
return $http({'url' : 'data.json', 'method' : 'GET'}).then(function(response){
return response.data;
}, function(data){
console.log(data)
})
}
}
}]);
myApp.controller('users', ['$scope', '$http', 'userData', function($scope, $http, userData){
userData.userslist().then(function(data){
//var provideDataKey = Object.keys(data.users)[0];
$scope.items = [];
angular.forEach(data, function(item){
//console.log(item.users);
$scope.items.push(item.users)
})
console.log($scope.items)
})
}]);
response is the HTTP response, with its body (data), headers, etc.
So response.data is the body, which looks like this:
{
"data": {
"new": true,
"show_page": false,
"status": "signedin",
"users": [{
"Michele": {
"logo": "xyz.jpg",
"status": "active",
"active_since": 2015,
"order": 1
},
"Gerry": {
"logo": "xyz.jpg",
"status": "active",
"active_since": 2015,
"order": 1
}
}]
},
"success": true
}
What you want is to access the users field of the data field of this body. So what you want is
userData.userslist().then(function(data){
$scope.items = data.data.users;
console.log($scope.items)
})
$scope. items is an array, not an object. You want to display the elements of this array. So the syntax is:
{{ user }}
Your JSON is awful, because each user is an object with a single field, and you have no way of knowing the name of that field. You'd better change it to
"users": [
{
"name": "Michele",
"logo": "xyz.jpg",
"status": "active",
"active_since": 2015,
"order": 1
},
{
"name": "Gerry",
"logo": "xyz.jpg",
"status": "active",
"active_since": 2015,
"order": 1
}
]
That way you could just do:
<li ng-repeat="user in items">
{{ user.name }}, active since {{ user.active_since }}.
use this
myApp.controller('users', ['$scope', '$http', 'userData', function($scope, $http, userData){
userData.userslist().then(function(data){
//var provideDataKey = Object.keys(data.users)[0];
$scope.items = [];
angular.forEach(data.users[0], function(item){
$scope.items.push(item);
})
console.log($scope.items)
})
}]);
you were iterating over data and not on users.
How to display the following json in scroll bar using angularjs mvc
myjson whixh i get from api localhost:port/details using nodejs:
[
{
"id": 4,
"notes": "sdas 123",
"invoice": "232",
"objectType": "Customer",
"objectId": 5,
"dateCreated": "2015-09-29T22:54:06.000Z",
"dateModified": "2015-10-08T23:01:16.000Z"
},
{
"id": 10,
"notes": "sample Test",
"invoice": "123",
"objectType": "Customer",
"objectId": 5,
"dateCreated": "2015-09-30T06:38:52.000Z",
"dateModified": "2015-09-30T01:20:38.000Z"
}
]
Any help guys..?
yes i have started and tried like this :in my controller
my config as:
angular.module('customerdetails).config(['$stateProvider',
function($stateProvider) {
$stateProvider.
state('listCust', {
url: '/details',
templateUrl: "/customerdetails/views/listcustomer.client.view.html'
});
}
]);
my service:
angular.module('customer').factory('Customer',function($resource)
{
return $resource('/details');
});
my controller:
angular.module('customerdetails').controller('CustomerController', ['$scope', '$rootScope', '$state', '$stateParams', '$location', 'Authentication', 'Customer', 'InvoiceRefund', '$filter',
function ($scope, $rootScope, $state, $http, $stateParams, $location, Authentication, Customer, $filter) {
var cus = Customer.query(function() {
console.log(cus);
});
To display JSON data you can use follwoing syntax: {{variable | json}} in the template, but for that you need to assign $scope.variable = YOUR_JSON; in your controller code
hi i have a JSON like this:
pages[
{
"id": "74682309",
"labels": [
{
"term": "test1",
"probability": 0.069
},
{
"term": "test2",
"probability": 0.037
}
]
}];
and using tags-input i want the tags to read only the term and show the term so i can show and update.
i have
<tags-input ng-model="se.labels"></tags-input>
the 'se' comes from ng-repeat="se in searchCtrl.pages
Based on the documentation (http://mbenford.github.io/ngTagsInput/documentation/api) you can change the keyProperty and displayProperty to make it use "term" instead of "text"
I've created a fiddle to demonstrate how you can obtain the data needed, considering that the provided JSON is a valid JSON. Your JSON is invalid.
var myApp = angular.module('myApp',['ngTagsInput']);
myApp.factory('data', function() {
var data = [
{
"id": "74682309",
"labels": [
{
"text": "test1",
"probability": 0.069
},
{
"text": "test2",
"probability": 0.037
}
]
}];
return data;
});
myApp.controller('MyCtrl', ['$scope', 'data', function($scope, data) {
var values = [];
data.map(function(elem) {
return elem.labels.forEach(function(el) {
values.push({
"text" : el.text
});
});
});
$scope.tags = values;
}]);
And the html part:
<div ng-controller="MyCtrl">
<div class="elem">
<tags-input ng-model="tags"></tags-input>
</div>
</div>
Here is the fiddle:
http://jsfiddle.net/HB7LU/16554/
Update:
You haven't included the angular ng-tags-input extension as a tag into your question. Please see my updated fiddle:
http://jsfiddle.net/HB7LU/16557/
I have a UserAddController and I want to be able to access a list of countries returned by a Web API. The Web API returns data fine. Here is my app.js where I get the data :
app.factory('Country', function ($resource) {
return $resource(
"/api/country/:Id",
{ Id: "#Id" },
{ "update": { method: "PUT" } });
});
This is my Controller :
var UserAddController = function ($scope, $location, service, User) {
$scope.action = "Add";
$scope.countries = service.countries;
};
I am declaring and creating a service here :
app.factory('CountryService', CountryService);
function CountryService($resource) {
return $resource(
"/api/country/:Id",
{ Id: "#Id" },
{ "update": { method: "PUT" } });
}
I am using the same code as above just for testing purposes. I am injecting this service like this :
UserAddController.$inject = ['$scope', 'CountryService'];
This is my first attempt at dependency injection and I cannot figure out where I am going wrong. The error I currently get is 'service is undefined'. I have tried passing both the service and the Country object to the Controller with the same results. Can anybody give any advice?
EDIT : In my Controller, this populates successfully with an alert in the code, but without the alert does not populate. Any reason why this is?
function CountryService($rootScope, $http) {
var self = {};
//self.countries = [{ "$id": "1", "CountryId": 1, "CountryName": "United Kingdom" }, { "$id": "2", "CountryId": 2, "CountryName": "Republic of Ireland" }, { "$id": "3", "CountryId": 3, "CountryName": "Australia" }, { "$id": "4", "CountryId": 4, "CountryName": "New Zealand" }, { "$id": "5", "CountryId": 5, "CountryName": "United States" }, { "$id": "6", "CountryId": 6, "CountryName": "France" }, { "$id": "7", "CountryId": 7, "CountryName": "Germany" }, { "$id": "8", "CountryId": 8, "CountryName": "Finland" }];
$http({
method: 'GET',
url: '/api/country'
}).success(function (data, status, headers, config) {
self.countries = data;
});
alert(self.countries);
return self;
}
You need to add other services/dependencies.
UserAddController.$inject = ['$scope',
'$location',
'CountryService',
'UserService'];
I have assumed that last dependency is a service with name 'UserService'. It's signature would be
app.factory('UserService', UserService);
Edit :
You need to instantiate a new variable.
//Inside function body
$scope.countries = service.countries;
$scope.newCountry = $scope.countries.get({Id : someId},callbackFn);
Now you have a counrtry with 'someId' in $scope.newCountry
Make sure you injected ngResource.
app = angular.module("app", ['ngResource']);
You need to inject the modules correcly
UserAddController.$inject = ['$scope', '$location', 'CountryService', 'user'];
This is quoted the doc.
You can specify the service name by using the $inject property, which
is an array containing strings with names of services to be injected.
The name must match the corresponding service ID registered with
angular. The order of the service IDs matters: the order of the
services in the array will be used when calling the factory function
with injected parameters.
I created a FIDDLE and you can try.