ng-model having a string value and ng-option integer - javascript

Here is my JSON array:
array=[ {id:1, name:'A'} , {id:2, name:'B'} ]
And in ng-model I am setting value which may be string like
modelValue='1'
I had ng-option
ng-option="option.id as option.name for option in array"
ng-model="modelValue"
But it is not showing selected value of ng-model in select

And in ng-model I am setting value which may be string like
You should provide the same primitive or object type to your $scope.modelValue as of id. This is the preferred way.
If only the JSON array is being fetched dynamically AND type consistency is not guaranteed then you can apply a function to convert it to the type that is set to $scope.modelValue
In HTML
<select ng-model="modelValue" ng-options="getId(option.id) as option.name for option in myarray">
</select>
In Controller
$scope.modelValue='1';
$scope.myarray=[ {id:1, name:'A'} , {id:2, name:'B'} ];
$scope.getId = function(id)
{
if(typeof $scope.modelValue == "string")
return String(id);
else if(typeof $scope.modelValue == "number")
return parseInt(id);
}
COMPLETE EXAMPLE
Also see this answer

Here is a working JSFiddle example based on your description: http://jsfiddle.net/9pLdgmm1/1/
You should use ng-options instead of ng-option
<select ng-options="p.name for p in people"
ng-model="selectedPerson">
</select>

You should take ng-options instead of ng-option, als you should take integer itself instead of string..
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-model="modelValue" ng-options="option.id as option.name for option in names">
</select>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.names = [ {id:1, name:'A'} , {id:2, name:'B'} ]
$scope.modelValue = 1;
});
</script>
<p>This example shows how to fill a dropdown list using the ng-options directive.</p>
</body>
</html>
Please run the above snippet
Here is a Working DEMO

This should not be selected, because of all id is in numbers. If you want to make it select, then parse your $scope.modelValue to numbers like this.
$scope.modelValue= parseInt("1");
Also change your ng-options instead of ng-option

You have a syntax error in ng-options:
<select ng-options="option.name for option in array" ng-model="modelValue"></select>
var myapp = angular.module('myapp', []);
myapp.controller('FirstCtrl', function($scope) {
$scope.array = [{
id: 1,
name: 'A'
}, {
id: 2,
name: 'B'
}];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp">
<fieldset ng-controller="FirstCtrl">
<select ng-options="option.name for option in array" ng-model="modelValue"></select>
modelValue is: {{modelValue}}
</fieldset>
</div>

Related

angularjs - setting select element option value with JS object

I am new to AngularJS so please bear with me.
Following is the the JSON string I am trying to bind in the select element:
[
{"Name":"Value 1","ID":1},
{"Name":"Value 2","ID":2},
{"Name":"Value 3","ID":3},
{"Name":"Value 4","ID":4}
]
Following is the JS object for the same:
function NameValue(nameValue){
var self = this;
self.ID = nameValue.ID;
self.Name= nameValue.Name;
}
I am parsing the above JSON string, looping through the objects and pushing items into an array using the above JS object like:
angular.forEach(angular.fromJson(jsonString), function (value, key) {
$scope.Values.push(new NameValue(value));
});
Following is my select with agularjs bindings:
<select ng-model="SelectedName" ng-options="x.Name for x in Values">/select>
When I select a value in the select element, the entire NameValue object is getting set into the SelectedName property which is what I am trying to do.
Now when I try to set the SelectedName property dynamically, the value is not getting selected and an empty option element is getting added in the select element. I used the {{SelectedName}} to check the value when set dynamically and when I select the same value in the select element manually and both are {"ID":2,"Name":"DAO"} which are exactly same. What am I doing wrong here?
The syntax of ng-options is something like this.link
<select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select>
Suppose you have controller like this
app.controller('MainCtrl', function($scope) {
$scope.Values = [
{"Name":"Value 1","ID":1},
{"Name":"Value 2","ID":2},
{"Name":"Value 3","ID":3},
{"Name":"Value 4","ID":4}
];
$scope.SelectedByName='Value 2'; //Default setting drop down by Name property
$scope.SelectedById=4; //Default setting drop down by ID property
});
If you follow the below syntax then either name or Id property will be set to selected variable.
If you need default selection of drop down then you need to set the respective model in controller.(as above)
HTML :
<body ng-controller="MainCtrl">
By name :
<select ng-options="value.Name as value.Name for value in Values"
ng-model="SelectedByName" ng-change="Print()"></select>
Selected value is : {{SelectedByName}}
<br>
By ID :
<select ng-options="value.ID as value.Name for value in Values"
ng-model="SelectedById" ng-change="Print()"></select>
Selected id is : {{SelectedById}}
</body>
Demo plunker Click here
First of all - you should initialize SelectName in your $scope.
Next you can use:
ng-options="x.id as x.name for x in values"
Can you display {{values}} in your template and it's look good? Maybe you have a problem with redraw template when data is push into value. Check this way also.
here is a working snippet. i guess you didn't defined Values as an array, before pushing anything you have to define the variable as an array.
var app = angular.module('myApp', []);
function NameValue(nameValue) {
var self = this;
self.ID = nameValue.ID;
self.Name = nameValue.Name;
}
app.controller('myCtrl', function($scope) {
$scope.Values = [];
$scope.jsonString = [{
"Name": "Value 1",
"ID": 1
}, {
"Name": "Value 2",
"ID": 2
}, {
"Name": "Value 3",
"ID": 3
}, {
"Name": "Value 4",
"ID": 4
}];
angular.forEach(angular.fromJson( $scope.jsonString), function (value, key) {
$scope.Values.push(new NameValue(value));
});
console.log($scope.Values);
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-model="SelectedName" ng-options="x.Name for x in Values">/select>
</div>
</body>
</html>
I had the same issue and i found a solution:
Don't use ng-options but <option> tag
<select ng-model="..."> <option ng-repeat="..."> {{ ... }} </option></select>

Angular 1.5 "track by" ruines binding in ng-options

I need to select option in combobox from ajax loaded data. That data comes as list of objects. The problem is that ng-option compares objects by reference and thus setting model to objects element results in appearing new empty option in combobox instead of selecting correct option.
The known workaround is to use track by expression.
And here is example code:
var myApp = angular.module("myApp", []);
myApp.controller("myCtrl", function($scope) {
$scope.roles =[
{ key:"administrator", value:"ROLE_ADMIN" },
{ key:"operator", value:"ROLE_OPERATOR" },
];
// this emulates data from server
// won't work without 'track by'
$scope.role={ key:"administrator", value:"ROLE_ADMIN" };
});
Template:
<body ng-app="myApp" ng-controller="myCtrl">
0: <input ng-model="roles[0].key" />
<br>
1: <input ng-model="roles[1].key" />
<br>
select role: <select ng-model="role" ng-options="r.key for r in roles track by r.value">
</select>
<pre>selected role={{role|json}}</pre>
</body>
Here another problem arises. When one selects role in combobox and then
changes it's "key" property in textbox, then selected role stays unchanged. So it looks like binding is suddenly gets broken.
https://jsfiddle.net/xLqackxw/8/
from Angular documentation https://docs.angularjs.org/api/ng/directive/ngOptions
<select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select>
So:
<select ng-model="role" ng-options="r as r.key for r in roles track by r.value"></select>
'$scope.role' value will be object like { key:"administrator", value:"ROLE_ADMIN" } or { key:"operator", value:"ROLE_OPERATOR" }

Element got removed after applying filter

I am applying filters to get the data of a particular field through a dropdown, but when I select any option the filter applied elements get removed. How can I resolve it?
HTML code:
<body ng-controller="MyCtrl">
<div>
<label>Country filter</label>
<input type="text" ng-model="countryFilter" />
<label>Order by</label>
<select ng-model="selectedOrder">
<option ng-repeat="option in options">{{option}}</option>
</select>
</div>
<ul>
<li ng-repeat="detail in details | filter:{loc : selectedOrder}">{{ detail.country }}</li>
</ul>
</body>
JS code:
var app = angular.module('plunker', []);
app.controller('MyCtrl', function($scope) {
// order by options
$scope.options = ['1', '2', '3'];
// all countries
$scope.details = [{
id:1, country:'Finland', address:'Mainstreet 2',detail:[{
loc:'1'
}]
},{
id:2, country:'Mexico', address:'Some address',detail:[{
loc:'2'
}]
},{
id:3, country:'Canada', address:'Snowroad 45',detail:[{
loc:'3'
}]
}];
});
I want to filter through options and loc value. Where am I going wrong?
You don't need to write a custom filter.
Change your filter to: filter:{detail: {loc:selectedOrder}}
I added <option value=""></option> to the dropdown and set $scope.selectedOrder = ""; in order to show all countries by default.
Codepen
filter:{prop:value} returns objects which have property prop at first level, it does not watch in object deeper. (When usual filter without params does it)
Your objects in array details do not have 'loc' property. So nothing fits filter.
You can not filter by exact property of 2nd and deeper levels of object with standard angular filter. Implement your own or change data.

how to show tags using select2 in select tag using angularjs

I want to set the tags in in drop down usning select2. Like i want to put custom e-mail or anything else then it should show as tag.
I am sharing the jsfiddle.
<div ng-controller="MyCtrl">
<label>Please select items:</label>
<select ui-select2 multiple ng-model='selectedDaltons'>
<option ng-repeat="d in daltons" ng-bind="d" value="{{ d }}"></option>
</select>
</div>
var myApp = angular.module('myApp', ['ui.select2']);
function MyCtrl($scope) {
$scope.daltons = [
'Joe',
'William' ,
'Jack' ,
'Averell' ,
'Ma'
];
$scope.selectedDaltons = 'joe'; // Averell is preselected
};
http://jsfiddle.net/hWXBv/179/
In ui-select, you can use the 'tagging' feature, you can even set the tagging-label.
Check out this link
https://github.com/angular-ui/ui-select/wiki/ui-select
And this plunker:
http://plnkr.co/edit/m1SQXUxftBLQtitng1f0

Jquery + angularjs If statement working but href value not changing

Ive run into a little problem and I can't seem figure out where ive went wrong.
I am trying to change an href value outside of the select field when it changes. Console is logging properly but href is not changing.
**I would like the href value to change and contain text + an angularjs data like so "http://test.com/{{ch.names}}"
here is my select:
<select class="form-control3" name="ch" id="ch">
<optgroup label="Ch">
<option value="x6">x6</option>
<option value="P4">P4</option>
</optgroup>
</select>
this is the href attempting to change:
{{ch.names}}
and here is my jquery:
<script type="text/javascript">
$(document).ready(function() {
$("#ch").change(function() {
if($(this).val() == 'P4') {
$(".a-class").attr("href", "http://test.com/{{ch.names}}");
console.log(".a-class");
}
else {
$(".a-class").attr("href", "http://test2.com/{{ch.names}}");
console.log(".a-class1");
}
});
});
</script>
when the values are changed it will log the class or class1 fitting the if statement but my href does not change where have I went wrong?
It would be a lot cleaner to simply do this with Angular:
<div ng-app="TestApp">
<div ng-controller="TestController">
<select ng-model="selected" ng-options="option for option in options"></select>
<a ng-href="http://test.com/{{selected}}">Selected: {{selected}}</a>
</div>
</div>
Controller
var myApp = angular.module('TestApp',[]);
myApp.controller('TestController', ['$scope', function($scope) {
$scope.options = ['x6', 'P4'];
$scope.selected = 'P4';
}]);
Fiddle: here
EDIT
From your comment, it sounds like you want to switch the whole URL to something else depending on the selection. You could save that data as a property in an array of objects, like this:
myApp.controller('TestController', ['$scope', function($scope) {
$scope.options = [
{
title: 'x6',
urlPrefix: 'http://test1.com/'
}, {
title: 'P4',
urlPrefix: 'http://test2.com/'
}];
$scope.selected = $scope.options[1];
}]);
You'll need to change the HTML a little:
<select ng-model="selected" ng-options="option.title for option in options"></select>
<a ng-href="{{selected.urlPrefix}}{{selected.title}}">Selected: {{selected.title}}</a>
Updated fiddle: here
The angular way to do this is not to use jQuery at all. You create an app and a controller, bind the values and let angular take care of it. Plunkr
Html:
<body ng-app="TestApp">
<div ng-controller="TestCtrl">
<select class="form-control3" name="ch" id="ch" ng-model="href_value" ng-options="value.data group by value.group for value in opt_values"></select>
{{href_value.data}}
</div>
</body>
Javascript:
angular.module('TestApp', [])
.controller('TestCtrl', ['$scope', function($scope) {
$scope.opt_values = [
{data: 'x6', url: "http://test.com/", group: "Ch"},
{data: 'P4', url: "http://test2.com/", group: "Ch"}];
}]);

Categories

Resources