Unable to bind data in angular 2 - javascript

I'm trying to bind countries data into my px-component which is a typeahead.
Codepen link here.
On binding the data directly in html the typeahead is suggesting the list of countries. But when I try the same by passing data from class its not binding.
var AppComponent = ng
.Component({
selector: 'my-app'
})
.View({
template: `<div>
<h3>Case 1 : Working dropdown:</h3>
<px-typeahead placeholder="Enter your search query" local-candidates='["Alabama","Alaska","American Samoa","Arizona","Arkansas","California","Colorado","Connecticut","Delaware","District Of Columbia", "South Dakota","Tennessee","Texas","Utah","Vermont","Virgin Islands","Virginia","Washington","West Virginia","Wisconsin","Wyoming"]'></px-typeahead>
<br>
<h3>Case 2 : Not working dropdown if data is bind from controller:</h3>
<px-typeahead placeholder="Enter your search query" local-candidates={{countries}}></px-typeahead>
{{countries}}
</div>`
})
.Class({
constructor: function() {
this.countries=["United States", "Antigua and/or Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan"]
}
});
Think the component px-typeahead is expecting the data in its attribute local-candidates to be an array with ''.
I tried different ways of binding countries like {{countries}},"countries" etc.But didn't work.

The correct syntax (for two-way data binding) is [local-candidates]="countries", which will work in your CodePen.

Related

Ionic get integer ID from JSON data

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

Consulting and returning data from JSON file in angular.js

I'm new with angularjs, and I have some background from PHP and Rails.
I'm making a simple app for studying purposes, and in this app I'll be asking for for a Capital and giving the State, and vice versa.
I'm okay with ui-router and a lot of things I didn't know about angular, but I'm having troubles specially with de data fetching.
My service for de capital --> state functionality is:
.factory('CidadeFactory', ['$http', function($http) {
var vm = this;
vm.data = []
return $http.get('../dados.json')
.success(function(data) {
vm.data = data;
console.log(data)
})
.error(function(err) {
console.log(err);
})
My controller (with no functions yet) is something like this:
angular.module('appUi').controller('CidadeCtrl', ['CidadeFactory',function(CidadeFactory){ }])
The html for this state is:
<form action="">
<fieldset>
<label for="input-cidade">Type the capital name</label>
<input type="text" />
</fieldset>
</form>
and my .json :
{"itens": [
{ "state": "Rio Grande do Sul", "capital": "Porto Alegre " },
{ "state": "Santa Catarina", "capital": "Florianópolis" },
{ "state": "Paraná", "capital": "Curitiba" },
{ "state": "São Paulo", "capital": "São Paulo" },
{ "state": "Rio de Janeiro", "capital": "Rio de Janeiro" },
{ "state": "Minas Gerais", "capital": "Belo Horizonte" },
{ "state": "Espirito Santo", "capital": "Vitória" } ]}
My question is:
What should I do to get the value of the input, consult in my json file where this value is return the relative state.
For example:
If the form value is Curitiba, I should return Paraná.
Should I use underscore.js for data manipulation?
And for best-pratices reasons:
Is it the better way to keep the data fetching on the factory, and the data manipulation on the controller, or there's a better aproach for this?
AFAIK a common way to establish the link is to watch the model of the textfield in the controller and bind a callback-function to it, which retrieves the data from the factory.
underscore.js for data-manipulation sounds like a good idea, I don't see any problems with that.
In the template:
<input type="text" ng-model="enteredCapital" />
and
Your state is {{state}}
In the controller:
$scope.$watch('enteredCapital', function() {
//call factory and do your thing
$scope.state = state; //return the state-value back to the template
});

Angulajs ng-options from a json with child object

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

Select default value with condition in ng-options

I have an angular app with the following array:
countries = [{"code": "ZA", "name": "South Africa"}, {"code": "CH", "name": "Switzerland"}]
with a Jade select as follow:
select(ng-model='myCountry', ng-options='country.name for country in countries')
What I would like to do is to pre-select a country based on the code for example:
select(ng-model='myCountry', ng-options='country.name for country in countries', ng-selected='country.code=="CH"')
Obviously, this solution doesn't work as ng-selected is not intended to be used in a select but in an option tag.
It is important for me to use a conditional selection and not a default index value like in the angularJS example.
From your sample above it looks like you should do this in your controller:
$scope.myCountry = $scope.countries.filter(function(c){ return c.code==="CH"})[0];
Like this:
<script>
function MyCntrl($scope) {
$scope.countries = [{"code": "ZA", "name": "South Africa"}, {"code": "CH", "name": "Switzerland"}];
$scope.myCountry = $scope.countries.filter(function(c){ return c.code==="CH"})[0];
}
</script>
Or you could try building the select with and ngRepeat which seems to be closer to what you need, like this:
Online Demo
<body ng-app="">
<script>
function MyCntrl($scope) {
$scope.countries = [{"code": "ZA", "name": "South Africa"}, {"code": "CH", "name": "Switzerland"}];
}
</script>
<div ng-controller="MyCntrl">
<select ng-model="myCountry" >
<option ng-selected="c.code=='CH'" ng-repeat="c in countries">{{c.name}}</option>
</select><br>
{{myCountry |json}}
</body>
That is what ng-model is for. I suggest you initialize myCountry in a controller. Note that myCountry should ideally have the same format as countries (eg: {"code": "ZA", "name": "South Africa"}).
Edit: I am adding an example from my own project:
<select class="small" data-ng-change="goToTask(current_task.id)" data-ng-model="current_task" data-ng-options="task.name for task in tasks track by task.id"></select>
In Controller:
$scope.current_task = { id: $scope.myService.getCurrentTaskId() };
What is important here is that current_task is at minimum a hash containing the id key.
Edit2: I was thinking about the sorting problem with the track by. I think you can use select instead, eg: `ng-options="select country.code as country.name for country in countries". I haven't tried it but from the angular docs, it should work.

AngularJS ng-repeat - http.gs retrieving data, but not displaying

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
}
]

Categories