How to create a drop down from API JSON data - javascript

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>

Related

Why does select option using angularJs show first empty option?

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>

Function in Controller not being hit

First time asking a q, so if I'm doing something wrong, please let me know so I can fix it as I have tried finding the answer on here, but can not, so any and all help would be greatly appreciated.
I'm trying to load a list of "Countries" using a controller and all seems to be going well, no errors, no warnings, it loads the module and hits the angular controller, but it never hits the function/goes into the code inside the function of the controller. Am I missing something? Am I doing something wrong?
Register.cshtml
<div ng-app="RegisterApp" class="form-group" ng-controller="CountriesController as CountriesCtrl">
<label class="input-desc">Country</label>
<select ng-model="country"
ng-options="country.Id as country.Name for country in countries">
<option value="{{CountriesCtrl.country.Id}}">{{CountriesCtrl.country.Name}}</option>
</select>
</div><!-- End .from-group -->
RegisterApp.js
var app = angular.module("RegisterApp", []);
CountriesService.js
/// <reference path="../App.js" />
angular.module("RegisterApp").service("CountriesService", function ($http) {
this.getCountries = function () {
return $http({
method: "Get",
url: "/Account/GetCountries"
});
};
});
CountriesController.js
/// <reference path="../Services/CountriesService.js" />
angular.module("RegisterApp").controller("CountriesController", function ($scope, CountriesService) {
getCountries();
function getCountries() {
CountriesService.getCountries()
.success(function (data, status, headers, config) {
$scope.countries = data;
$scope.country = $scope.countries[0];
})
.error(function (data, status, headers, config) {
$scope.message = 'Unexpected Error';
});
}
});
Edit: Moved the ng-app, was mistakenly copied over like that, was a change I made just to try something before posting the q, sorry for that
ng-app must be registered before ng-controller (Or on same element). You have registered it in a child-element (select) to the element with ng-controller
Change your HTML to:
<div ng-app="RegisterApp" class="form-group" ng-controller="CountriesController as CountriesCtrl">
<label class="input-desc">Country</label>
<select ng-model="country"
ng-options="country.Id as country.Name for country in countries">
<option value="{{CountriesCtrl.country.Id}}">{{CountriesCtrl.country.Name}}</option>
</select>
</div>
Have a look at this JSFiddle.
Your code must be:
<div ng-app="RegisterApp">
<!-- some beautiful html -->
<div class="form-group" ng-controller="CountriesController as CountriesCtrl">
<label class="input-desc">Country</label>
<select ng-model="country" ng-options="country.Id as country.Name for country in countries">
<option value="{{CountriesCtrl.country.Id}}">{{CountriesCtrl.country.Name}}</option>
</select>
</div>
<!-- some beautiful html -->
</div>
Notice ngApp directive usage.
Also, check that all of your dependencies are injected correctly (I mean <head> block)

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"}];
}]);

Angular JS - get selected text as ng model (without ng-options)

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

calling a HTTP get method to populate the result in drop down using angular JS

I have all controllers defined at one place.
$routeProvider.when(pages.hello,
{
templateUrl: 'test/hello.html',
controller: 'myController',
access: access.anon,
helloPage: 'arf'
});
My hello.html looks like this.
<select name="chooseFunc" data-ng-model="choosenFunction" class="input-xlarge ng-pristine ng-valid" data-ng-click="fetchID()" data-ng-change="update(choosenFunction)">
<option value="ABCD">ABCD</option>
<option value="CDEF">CDEF</option>
</select>
Now I want to call a http get method "/abc/hello" to populate the drop down like ABCD, CDEF values based on it.
I have written some thing like this.
$scope.fetchID = function() {
console.log("hello in fectch id");
$http.get('/abc/hello').success(successCallback).error(error);
};
My function is not getting called. Could some help me with the following.
Calling fecthID() function on page load.
fechID() function should populate the options in select element.
I am new here. Can some one help me.
I would write controller like:
function myController($scope,$http) {
$scope.values = [{id:"ABCD",Name:"David"},{id:"CDEF",Name:"John"}];
$scope.selectedItem = $scope.values[0].id;
$scope.fetchID = function() {
$http.get('/abc/hello').success(
function(data, status, headers, config){
$scope.values.push(data);// play here
})
.error(error);
};
$scope.fetchID(); // call
}
and hello.html with init first combo value:
<select name="chooseFunc"
ng-model="selectedItem"
ng-options="selectedItem.id as selectedItem.id for selectedItem in values"
class="input-xlarge ng-pristine ng-valid"
data-ng-click="fetchID()"
data-ng-change="update(choosenFunction)"
></select>
You can use ng-options to populate select like
<select ng-model="mySelecetdValue" ng-options="item for item in items">
</select>
To Call fecthID(), Just call it like
$scope.fetchID()
And Populate items in successCallback function

Categories

Resources