I am new to angular and trying to integrate it within my application. I am attempting to use a simple $http.get to a .JSON file, which displaying the matching contents in a ng-repeat
Here my get:
$scope.countries = [];
$http.get('/resources/data/countries-report.json').success(function(data) {
$scope.countries = data.countries;
// alert(JSON.stringify($scope.countries));
console.log(data.countries);
console.log(data.countries.population);
}).error(function(error) {
alert('error');
});
Here's my .JSON file:
{
"firstName" : "Joe",
"surName" : "Bloggs",
"countries" : [
{ "name": "France", "population": "63.1" },
{ "name": "Span", "population": "52.3" },
{ "name": "United Kingdom", "population": "61.8" }
]
}
Here is my HTML:
<li ng-repeat="country in countries">
{{country.name}} has population of {{country.population}}
</li>
When viewing in the browser, all that is displayed is:
has population of
has population of
has population of
It seems as though my code can see there are 3 countries, as when i add or remove from my .JSON file, the list in the HTML modifies accordingly, however, the contents of the .JSON is not displaying.
Have i forgot to return the data from my .get??
** UPDATE *************************
As some have mentioned, my code seems to be correct, i think i know what the problem may be.
My application makes use of a HTML templating structure using Swig which accesses .JSON file using {{ }}.. Could this be causing confusion with Angular?
** UPDATE *************************
If i change:
var app = angular.module("app", []);
to
var app = angular.module('app', []).config(function($interpolateProvider){
$interpolateProvider.startSymbol('{[{').endSymbol('}]}');
}
);
And:
<li ng-repeat="country in countries">
{{country.name}} has population of {{country.population}}
</li>
To:
<li ng-repeat="country in countries">
{[{country.name}]} has population of {[{country.population}]}
</li>
Then the correct values are displayed.
you have to get the data in the array of object form like
[
{
id:1,
ima:gh.jpg,
data:
[
{
anotherid:1,
my:w,
ki:y
}
]
},
{
id=2,
ima:jh.jpg
}
]
Related
iam newbie and i want to ask.
i want to get some value from JSON API (title, course_id, etc), and put the Value to my Template with Directive. so at Index, i can repeat my tempalate with data from the API.
How to get Value from that JSON ?
This my Code :
my API
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"url": "http://192.168.1.37:8000/api/courses/a/",
"title": "I Love You", <-- I want to put this Value to my Template
"course_id": "1",
"starting_date": "2016-10-03"
}
]
}
Controller demo.js
demo.controller("demo", function($scope, $http) {
$http.get('http://192.168.1.37:8000/api/courses/'). <-- Data From my API
then(function(response) {
$scope.courses = response.data;
});
});
demo.directive("demoItemDirective", function() {
return {
scope : { demoInfo : "=info"},
templateUrl : "/app/demo.tmpl" <-- My Template
};
});
My Template demo.tmpl
<p>{{demoInfo.count}}</p> <-- Works, count Displayed
<p>{{demoInfo.results.title}</p> <-- Not works, title not displayed
My Index.html
<div ng-repeat="group in courses | groupCount:2">
<div ng-repeat="x in group">
<demo-item-directive info="x"></demo-item-directive>
</div>
</div>
It should be
<p>{{demoInfo.results[0].title}</p>
Your result contain an Array of object.
You need to access with index.
According to your post, the result is an array:
"results": [
{
"url": "http://192.168.1.37:8000/api/courses/a/",
"title": "I Love You", <-- I want to put this Value to my Template
"course_id": "1",
"starting_date": "2016-10-03"
}
]
Thus, you can't refer to the title itself, you have to reference the first element:
{{demoInfo.results[0].title}}
This should be a very simple thing to do. I am building an IONIC app with a JSON data file. The data is something like this.
[
{ "id": 1,
"name": "John",
"type": "male",
"bio": "this is John"
},
{ "id": 10,
"name": "Mary",
"type": "female",
"bio": "this is Mary"
}
]
Now I want to filter by by "type" in the data and then loop the data by "id".
<ion-list ng-repeat="person in people | filter: {'type': 'male'}">
<ion-item href="#tab/people/males/{{ person.id }}">{{ person.name }}
</ion-item>
</ion-list>
The Controller for this is:
.controller('PeopleController', ['$scope', '$state', '$http', function($scope, $state, $http){
$http.get('data/people.json').success(function(data){
$scope.people = data;
$scope.whichPerson = $state.params.id;
}),
}])
This displays the required data of males only by name.
However if I want to see the individual bio using the following code
<div class="card" ng-repeat="person in people | filter: { id: whichPerson }">
<h2>{{ person.name }}</h2>
<p>{{ person.bio}}</p>
</div>
When I click the individual item for each person to display person.bio I get both John and Mary.'
I figured this was because the "id" is 1 and 10 which seems to be parsing as a string to the controller. I tried putting this
"id": "1" and "id": "10"
Did not work. I did this in the controller
$scope.whichPerson = parseInt($state.params.id, 10);
This does not work either. I am totally stumped. How do I get the individual id's from the data? In fact I noticed that I can change the id to 11 or 12 or 13 etc and it still returns both records?
Any help appreciated.
Try to add the comparator :true to your filter as described in the documentation. This forces a strict comparison of the filter value instead of just checking if the data contains it.
Given the above doesn't work, you could try a custom filter by doing:
filter: { id: whichPerson }:sameID
and then in your controller:
$scope.sameID = function(actual, expected) {
return parseInt(actual) === parseInt(expected)
};
Even if this doesn't work, you could then at least debug within the custom filter to see where the comparison is failing
I am trying to populate an angularjs ng-options with a json file that has child object, but i am finding it difficult getting it to work.
This is my controller script
inmomentControllerNameSpace.controller('userController', function($scope, $http, $q){
$scope.countryUserCode = {};
$http.get("js/countryCode.json").success(function(data){
$scope.countryUserCode = data;
$scope.tel = 'show';
})
})
})
My HTML Code
<select data-ng-options="name.countryUserCode for d in countryUserCode" data-ng-model="selectedCode"></select></select>
My Json File
{
"af": {
"name": "Afghanistan",
"phoneCode": "93"
},
"al": {
"name": "Albania",
"phoneCode": "355"
},
"dz": {
"name": "Algeria",
"phoneCode": "213"
}
}
What i intend to achieve is to have the name appear in the option label and the phone code appear in the option.
I will be glad if anyone can help me thank you....
Try this syntax for ngOptions:
<select data-ng-options="country.phoneCode as country.name for (isoCode, country) in countryUserCode" data-ng-model="selectedCode"></select>
Demo: http://plnkr.co/edit/7csZXkmY430LTLhf5D7g?p=preview
I would like to dynamically load select elements from an API request.
Here is my controller:
var myApp = angular.module('myApp',[]).controller('tripCtrl', function($scope){
//Call to API to get people
$scope.people = [
{
"id": 1,
"name": "Joe Hamlet"
},
{
"id": 2,
"name": "Mary Jane"
},
{
"id": 3,
"name": "Tom Lee"
}
];
//Call to API to get the element to load
$scope.selectElement =
{
"Options": "person[dynamicValue] as person[dynamicDisplayName] for person in people",
"DisplayName": "name",
"Value": "id"
};
//Dynamicly load properties
$scope.dynamicValue = $scope.selectElement.DisplayName;
$scope.dynamicDisplayName = $scope.selectElement.Value;
});
HTML:
<select ng-model="selectedPerson" ng-options="{{selectElement.Options}}">
<option value="">Select</option>
</select>
{{selectedPerson}}
I created a JSFiddle trying to accomplish this. http://jsfiddle.net/HB7LU/9493/
I found this question which I was able to implement, but when I tried to set the ng-options from the Element's Options property, it failed to load. When inspected the HTML the code looks to be set properly, but the model binding isn't working.
Edit 12/28/2014:
After updating the Angular version in the original JS Fiddle, it worked properly, however when I expanded to use an actually API, I found another issue with loading ng-options dynamically. Here is the more in depth JS Fiddle: http://jsfiddle.net/zjFp4/330/
Also here is my updated controller. The dataService.getElement() calls a hard coded string, where as the dataService.getElementFromApi() calls the same exact string, just from json-generator (which is the mock API). When inspected the objects set from the API, everything is there, so it must be an issue with the binding in Angular. Any ideas on how to fix this?
function tripCtrl($scope, dataService) {
//Call to API to get people
dataService.getPeople().then(
function (event) {
$scope.people = event;
},
function (s) {
console.log(s); }
);
//Call to API to get the element to load
$scope.selectElement = dataService.getElement();
dataService.getElementFromApi().then(
function (event) {
$scope.apiElement = event;
$scope.dynamicValue = $scope.apiElement.Value;
$scope.dynamicDisplayName = $scope.apiElement.DisplayName;
},
function (s) {
console.log(s); }
);
}
I have quite an interesting question (I hope) for all you AngularJS gurus out there. I am looking to create a dynamic list of form input fields based on a SELECT dropdown. As an example, we have a number of categories with each category having a set of specifications which are unique to that category. To help with the explanation we have the following:
Firstly, in the controller we start by initializing the models.
$scope.category = {};
$scope.category.specs = [];
Next we ready the data to be used in the form (actually retrieved from the server via $http). We also initialize a variable to the first element in the categories array.
$scope.categories = [
{ "id": "1", "name": "mobile", specs: [
{ "id": "1", "label": "Operating System" },
{ "id": "2", "label": "Camera type" } ] },
{ "id": "2", "name": "laptop", specs: [
{ "id": "1", "label": "Operating System" },
{ "id": "2", "label": "Graphics Card" } ] }
};
$scope.selectedCategory = $scope.categories[0];
In the form, we have a dropdown which when selected loads the appropriate input fields specific to that category. We use the ngRepeat directive to accomplish this. This is a dynamic list of fields based on $scope.categories.specs. (please note the ???)
<select ng-model="selectedCategory" ng-options="category.name for category in categories"></select>
<div ng-repeat="spec in selectedCategory.specs">
<label>{{spec.label}}</label>
<input type="text" ng-model="???">
</div>
Ultimately, when the user clicks the submit button, we would like to extract the category he/she has selected and then package it together with the specifications they have filled in. The post request should contain something like the following for instance (of course, I only included one spec item, but in reality there would be many):
{ "id": "1", specs [ { "id": "2", "details": "RADEON HD 8970M" } ] }
Unfortunately I am not really sure how to accomplish this. I need to somehow create an array for the spec model, and then ensure that both the ID and user entered data are appropriately extracted... what goes in the ??? and what do we do after? Any help would be much appreciated.
this is how I do it. I make a form, validate it with angular, and then when its valid I submit it with a function.
<form name="signup_form" novalidate ng-submit="signupForm()"></form>
$scope.signupForm = function() {
var data = $scope.signup;
$http({
method : 'POST',
url : 'http://yoursite.com/mail.php',
data : $.param(data), // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
})
.success(function(data) {
});
}
also if you want to look at another form validation system for angular check out http://nimbly.github.io/angular-formly/#!/ It may help you solve your current form system.
In the controller, initialize $scope.specDetails as follows:
$scope.specDetails = {};
angular.forEach($scope.categories, function (category, index1) {
$scope.specDetails[category.id] = {};
angular.forEach(category.specs, function (spec, index2) {
$scope.specDetails[category.id][spec.id] = '';
});
});
In the html, replace "???" with specDetails[selectedCategory.id][spec.id]