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.
Related
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.
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 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
}
]
I have a form that is used to edit a object and I can't select a value in the select box.
I have a json array which represents the to be edited and look like this:
$scope.item = [{
"objectID": "76",
"versionID": "0",
"versionName": "CURRENT",
"objectName": "xyz",
}]
now I am at the same time populating a select box from another json array that looks like this:
$scope.versions = [
{
"id": "0",
"description": "CURRENT",
"name": "CURRENT"
},
{
"id": "114",
"description": "description of Version 2",
"name": "version2"
},
{
"id": "126",
"description": "description of Version 3",
"name": "version3"
},
{
"id": "149",
"description": "description of Version 4",
"name": "version4"
}]
inside my webpage I am creating the select box as follows:
Version: <select ng-model="item.versionID"
ng-selected="item.versionID"
ng-options="version.name for version in versions"
required>
the select box is populating for me but it should be selecting the the value that matches the version in item. I have tried both versionID and versionName, I have even tried setting ng-selected="0" and that doesn't even work.
I have looked here on SO, the Angularjs site and googled and gone through countless tutorials but still having issues with this. I just can't seem to see what the issue is so any Help greatly appreciated
JSFiddle Added
Added a JsFiddle here
You can simple use ng-init like this
<select ng-init="somethingHere = options[0]" ng-model="somethingHere" ng-options="option.name for option in options"></select>
You can just append
track by version.id
to your ng-options.
It doesn't set the default value because your model isn't bound to the id or name properties, it's bound to each version object. Try setting the versionID to one of the objects and it should work, ie $scope.item.versionID = $scope.versions[2];
If you want to set by the id property then you need to add the select as syntax:
ng-options="version.id as version.name for version in versions"
http://jsfiddle.net/LrhAQ/1/
After searching and trying multiple non working options to get my select default option working. I find a clean solution at:
http://www.undefinednull.com/2014/08/11/a-brief-walk-through-of-the-ng-options-in-angularjs/
<select class="ajg-stereo-fader-input-name ajg-select-left" ng-options="option.name for option in selectOptions" ng-model="inputLeft"></select>
<select class="ajg-stereo-fader-input-name ajg-select-right" ng-options="option.name for option in selectOptions" ng-model="inputRight"></select>
scope.inputLeft = scope.selectOptions[0];
scope.inputRight = scope.selectOptions[1];
As per the docs select, the following piece of code worked for me.
<div ng-controller="ExampleController">
<form name="myForm">
<label for="mySelect">Make a choice:</label>
<select name="mySelect" id="mySelect"
ng-options="option.name for option in data.availableOptions track by option.id"
ng-model="data.selectedOption"></select>
</form>
<hr>
<tt>option = {{data.selectedOption}}</tt><br/>
</div>
<select ng-model="selectedCar" ><option ng-repeat="car in cars " value="{{car.model}}">{{car.model}}</option></select>
<script>var app = angular.module('myApp', []);app.controller('myCtrl', function($scope) { $scope.cars = [{model : "Ford Mustang", color : "red"}, {model : "Fiat 500", color : "white"},{model : "Volvo XC90", color : "black"}];
$scope.selectedCar=$scope.cars[0].model ;});
if you don't even want to initialize ng-model to a static value and each value is DB driven, it can be done in the following way. Angular compares the evaluated value and populates the drop down.
Here below modelData.unitId is retrieved from DB and is compared to the list of unit id which is a separate list from db-
<select id="uomList" ng-init="modelData.unitId"
ng-model="modelData.unitId" ng-options="unitOfMeasurement.id as unitOfMeasurement.unitName for unitOfMeasurement in unitOfMeasurements">