In my code behind, I fill up a DropDownList as follows (using VB)
ddlCountries.DataSource = dt ' dt is DataTable with columns "CountryCode" and "CountryName"
ddlCountries.DataTextField = "CountryName"
ddlCountries.DataValueField = "CountryCode"
ddlCountries.DataBind()
ddlCountries.Attributes.Add("ng-model", "CountryName")
Then client side, I have a select tag, which is filled with options from server side as below:
<select ng-model="CountryName">
<option value="IN">India</option>
<option value="US">United States</option>
<option value="ML">Malaysia</option>
<!-- and other 200+ records -->
</select>
I can't use ng-options here! Now, whenever I change the value from select, I get CountryName as IN, US, ML etc.. Moreover, I can't edit values of options because they're used in server side code.
Here I want CountryName as India, United States or Malaysia instead! What can I do?
What data is the server sending you?
Is it some array of objects like this?
var countries = [
{ name: 'India', code: 'IN'},
{ name: 'United States', code: 'US'},
{ name: 'Malaysia', code: 'ML'}
];
If yes, then you can easily use ng-options (even though you dont have to, its just better).
<select ng-model="CountryName"
ng-options="c.code as c.name for c in countries">
</select>
Or in the case that you actually are working with server side generated html page and no javascript objects, then its a little bit tricker:
(Supposing you can use JQuery):
view:
<select id="countryNameSelect" ng-change="setCountryName()">
<option value="IN">India</option>
<option value="US">United States</option>
<option value="ML">Malaysia</option>
<!-- and other 200+ records -->
</select>
controller:
$scope.countryName = '';
$scope.setCountryName = function() {
$scope.countryName = $("#countryNameSelect option:selected").html();
};
In PHP BackEnd array to Json Out: < ? php echo json_encode($arrayDemo); ? >
// Init Load
$(function () {
'use strict';
angular
.module('ngjsapp', [])
.controller('FormCtrl', ['$scope', function ($scope) {
var myArraySelect = <?php echo json_encode($arrayDemo); ?>
$scope.changeSenasaProvinciasId = function (id) {
console.log(myArraySelect[id]);
}
}]);
});
Only HTML Stact + jQuery
// Option 1
$(function () {
'use strict';
angular
.module('ngjsapp', [])
.controller('FormCtrl', ['$scope', function ($scope) {
$scope.changeSenasaProvinciasId = function () {
console.log($("#mySelectID option:selected").text());
}
}]);
});
Only HTML Stact + jQuery BEST
// Option 2
$(function () {
'use strict';
angular
.module('ngjsapp', [])
.controller('FormCtrl', ['$scope', function ($scope) {
var myArraySelect = $('#mySelectID option').each( function() {
myArraySelect.push({$(this).val() : $(this).text() });
});
$scope.changeSenasaProvinciasId = function (id) {
console.log(myArraySelect[id]);
}
}]);
});
Related
I'm a newbie to Webapi with AngularJS. I have a URL which will give data in JSON format, I need to catch only employeename from the given data and pit it in drop down list in AngularJS. Any help appreciated.
you can use $filter to filter out data from the Json array like below,
$filter('filter')(your json array, { column name: value}, true)
Hope this will help.
You can try this <select name="{{option.empname}}" ng-model="modelName" ng-options="option for option in empdetail">
</select>
For more detail, refer here
Please take a look at this simple full qualified demo fiddle.
View:
<div ng-controller="MyCtrl">
<select ng-model="selected"
ng-options="option.name for option in options"></select>
</div>
AngularJS application:
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope, $http) {
$scope.options = [];
$scope.selected = null;
$http({
method: 'GET',
url: 'https://jsonplaceholder.typicode.com/users'
}).then(function (result) {
$scope.options = result.data;
$scope.selected = $scope.options[0];
});;
});
The proper way to do it is using the ng-options directive. The HTML would look like this.
<select ng-model="selectedTestAccount"
ng-options="item.Id as item.Name for item in testAccounts">
<option value="">Select Account</option>
</select>
JavaScript:
angular.module('test', []).controller('DemoCtrl', function ($scope, $http) {
$scope.selectedTestAccount = null;
$scope.testAccounts = [];
$http({
method: 'GET',
url: '/your-api-url',
}).success(function (result) {
$scope.testAccounts = result;
});
});
You'll also need to be sure that angular is run on your HTML and that your module is loaded.
<html ng-app="test">
<body ng-controller="DemoCtrl">
....
</body>
</html>
When I reload the page, the first option is always empty. I want the option containing text Any Make to be the default select option. Here is the code for my view:
<select class="form-control" id="make" name="make" ng-init="Any Make" ng-model="makeSelected" ng-change="makeChanged()">
<option value="0" selected="selected"> Any Make</option>
<option ng-repeat="obj in makeData" value="{{obj.make_id}}"> {{ obj.make_name | uppercase }} </option>
</select>
here is my controller code:
.controller("homeController", function ($scope, makeData, $http) {
$scope.makeData = makeData;
$scope.makeChanged = function () {
$http({
method: "GET",
url: "homeService.asmx/GetModelById"})
.then(function (response) {
$scope.modelData = response.data;
})
}
})
just remove ng-init and in your model give default value
$scope.makeSelected = 0;
Here is a running fiddle for your code Click here
Fiddle for code with dynamic data Click here
If you aren't going to use ngOptions, at least get rid of that ng-init since it isn't a function, and in the controller function set $scope.makeSelected = 0;
Then you can remove the selected="selected" on that initial option, since the angularJS code will be handling what is selected.
See a demonstration below:
angular.module('app', [])
.value('makeData', [{
"make_id": 1,
"make_name": "cat"
},{
"make_id": 2,
"make_name": "dog"
},{
"make_id": 6,
"make_name": "monkey"
}])
.controller("homeController", function($scope, makeData, $http) {
//initialize the value associated with ng-model on the select list
$scope.makeSelected = 0;
$scope.makeData = makeData;
$scope.makeChanged = function() {
console.log('makeChanged');
//$http() request removed because we don't have access outside this domain for AJAX requests.
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="homeController">
<select class="form-control" id="make" name="make" ng-model="makeSelected" ng-change="makeChanged()">
<option value="0"> Any Make</option>
<option ng-repeat="obj in makeData" value="{{obj.make_id}}"> {{ obj.make_name | uppercase }} </option>
</select>
<div>makeSelected: {{makeSelected}}</div>
</div>
I have an data in below given format
{
USA: {
CA: { 'SAN FRANCISCO':['94188', '94158', '94143'] },
LA: { 'BATON ROUGE':['70898','70895','70891'] }
}
}
trying to add them to dependent drop downs namely Country, State, City and Zip code. I'm using ng-option but while getting the value for country dropdown its returning oject:16 instead of value.
$scope.countries = {
USA: {
CA: { 'SAN FRANCISCO':['94188', '94158', '94143'] },
LA: { 'BATON ROUGE':['70898','70895','70891'] }
}
}
$scope.GetSelectedCountry = function () {
$scope.strCountry = document.getElementById("country").value;
}
<b>Country:</b>
<select id="country" ng-model="statessource" ng-disabled="!type" ng-options="country for (country, states) in countries" ng-change="GetSelectedCountry()">
<option value=''>Select Country</option>
It is not the Angular way to get values.
You use <select ng-model="statessource" ...>, so the value of the select is stored in $scope.statessource.
This should works:
$scope.GetSelectedCountry = function() {
$scope.strCountry = $scope.statessource;
}
You have used an ng-model variable for your select tag, but you have not used that in your controller to get the selected value. There is no need to access the value using javascript dom selector, instead you can directly use the model value of the select tag $scope.statessource.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.countries = {
USA: {
CA: {
'SAN FRANCISCO': ['94188', '94158', '94143']
},
LA: {
'BATON ROUGE': ['70898', '70895', '70891']
}
}
}
$scope.GetSelectedCountry = function () {
$scope.strCountry = $scope.statessource;
console.log($scope.strCountry);
}
});
</script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<b>Country:</b>
<select id="country" ng-model="statessource" ng-options="country for (country, states) in countries" ng-change="GetSelectedCountry()">
<option value=''>Select Country</option>
</select>
</body>
</html>
If your only concern is to get the currently selected value each and every time a user changes it, your ng-model will already handle this case.
So, by using this
<select id="country" ng-model="statessource" ng-disabled="!type" ng-options="country for (country, states) in countries">
Angular would always apply its two-way-data-binding to store the currently selected option inside your $scope.statessource-variable.
Other than that, if you want to do other stuff related to a change of the selection, you can do the following:
<select id="country" ng-model="statessource" ng-disabled="!type" ng-options="country for (country, states) in countries" ng-change="GetSelectedCountry(statessource)">
$scope.GetSelectedCountry = function (newState) {
// Do something with your newState variable.
// Remember, $scope.statessource still includes the currently selected
// option
}
I hope that helped :)
The way to access the selected value of an OPTION nested in a SELECT is here:
var e = document.getElementById("country");
var value = e.options[e.selectedIndex].value;
var text = e.options[e.selectedIndex].text;
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"}];
}]);
What is the simplest way to add some commands to the end of the Angular select box?
E.g. I want to get a list like this:
Cat
Dog
Octopus
Browse…
All items except Browse are some data / ng-options, but Browse is a command and always present. It should not be actually selectable as an item, and should call a handler instead.
I suppose I could put this command into the list bound to ng-options and manage it as a special case, but that feels like a hack. Is there a proper approach to this?
Take a look at this, here when you select the browse it will open a dialog box
Working Demo
html
<form ng-app="app" ng-controller="Ctrl" ng-init="item = this">
<select ng-model="animal" ng-change="clickToOpen()" ng-init="animal='select'">
<option value="select">Please select an animal</option>
<option ng-repeat="animal in animalsGroup">{{animal.name}}
</option>
<option value="Browse..">Browse..</option>
</select>
<script type="text/ng-template" id="templateId">
<h1>Template heading</h1>
<p>Content goes here</p>
<center><input type="button" value="OK" ng-click="closeThisDialog(this)"/></center>
</script>
</form>
script
var app = angular.module("app", ['ngDialog']);
app.controller('Ctrl', function ($scope, ngDialog) {
$scope.animalsGroup = [
{name:'Cat'},
{name:'Dog'},
{name:'Octopus'}
];
// select initial value
$scope.animal = $scope.animalsGroup[0];
//
$scope.clickToOpen = function () {
if ($scope.animal === 'Browse..')
{
$scope.animal = "select";
ngDialog.open({
template: 'templateId',
className: 'ngdialog-theme-plain',
showClose: false,
});
}
else
{
// other than 'Browse'
}
};
$scope.closeThisDialog = function (dialog) {
dialog.close();
}
});
If i understood corectly you want to handle the browse option differently .
Script :
$scope.colors = [
{name:'Cat'},
{name:'Dog'},
{name:'Octopus'},
{name:'Browse'}
];
$scope.handleChange = function(){
if ($scope.myColor.name === 'Browse'){
// your implementation
}
}
Html :
<select ng-model="myColor" ng-options="color.name for color in colors" ng-change="handleChange"></select>