Angular $http.get changes from select box - angularjs

I'm not sure if this is going to make sense, I spent some time trying to research the answer I require.
I'm wanting to know if it is possible in angular to change the URL requested from a $http.get request from a value of a select box.
So I have built a simple controller which gets a JSON file and passes the response in to the scope, then I pass that data in to the view.
But I will have several JSON files which I want to load on selection of an option from a drop down and reload the data.
My Angular is fairly basic, so i'm unsure if this is at all possible to do on the fly?
var app = angular.module('serverstats', []);
app.controller('ServerController', function($scope, $http){
var apiFeed = $('.apiSelecter').val();
$http.get(apiFeed).then(function(response){
$scope.status = response.data;
$scope.server = [];
angular.forEach($scope.status.servers, function(svr) {
$scope.server.push(svr);
})
console.log('server', $scope.server);
});
});
<select class="apiSelecter">
<option value="/test.json">Data File 1</option>
<option value="/test1.json">Data File 2</option>
<option value="/test2.json">Data File 3</option>
</select>
<div ng-controller="ServerController" id="server-stats" class="server-stats">
<div ng-repeat="stat in server" class="container" ng-cloak>
<div class="stats-box col-md-2">
<p class="lead">Server Name: {{ stat.serverName }}</p>
</div>
<div class="stats-box col-md-2">
<p class="lead">Response Time: {{ stat.responseTime }}</p>
</div>
<div class="stats-box col-md-2">
<ul>
<p class="lead">Ports</p>
<li><p class="lead">{{ stat.ports.port1 }}</p></li>
<li><p class="lead">{{ stat.ports.port2 }}</p></li>
<li><p class="lead">{{ stat.ports.port3 }}</p></li>
<li><p class="lead">{{ stat.ports.port4 }}</p></li>
<li><p class="lead">{{ stat.ports.port5 }}</p></li>
</ul>
</div>
Apologies now included code

Of course you can.
HTML :
<select id="mySelect" ng-model="myValue" ng-change="myMethod()">
<option ng-repeat="o in options" value="{{o.url}}">{{o.label}}</option>
</select>
And in your controller
$scope.options = [
{url : 'www.google.com', label: 'google'},
{url : 'www.facebook.com', label:'facebook'}
]
$scope.myMethod = function() {
console.log($scope.myValue);
//HTTP Resquest here
}
The ng-change attribute will trigger when you change the selected option. The ng-model allows you to store the current value in memory.
After your HTTP request (in then .then) you can load your JSON and all the stuff you do.
NB : if your select is a Materialize one, use the angular-materialize library and use
<select id="mySelect" ng-model="myValue" ng-change="myMethod()">
<option ng-repeat="o in option" value="{{o.url}}" material-select watch>{{o.label}}</option>
</select>

Related

Binding ngModel input to form array in Angular

i want to create *ngFor binding to create another form using array and ngModel input.
So when i select the value in it, then i click the button to display new form with different value.
Any ideas how it should be worked?
I have tried this but the result is just same as the other ngModel value.
This is for Progress Tracker in my company, running on AngularJS 8 using Clarity-VMWare. I've tried using let i = index and it doesn't get the value.
HTML:
<div class="card card-report" *ngFor="let item of report">
<div class="card-block block-card">
<div class="card-title">
<div class="clr-wrapper">
<select class="clr-select-1" [(ngModel)]="selectedProjects">
<option [ngValue]="default" disabled>Project yang kamu kerjain apa?</option>
<option [ngValue]="item" *ngFor="let item of listProjects">
{{item.name}}
</option>
</select>
</div>
<div class="clr-wrapper">
<select class="clr-select-2" [(ngModel)]="selectedRoles">
<option [ngValue]="default" disabled>Kamu jadi apa di project ini?</option>
<option [ngValue]="item" *ngFor="let item of listRoles">
{{item.name}}
</option>
</select>
</div>
</div>
<div class="card-text text-card">
<p class="sub-text-card">Kamu belum melakukan apa-apa</p>
</div>
</div>
</div>
TS:
listProjects: any[]
listRoles: any[]
selectedProjects: any;
selectedRoles: any;
addReport() {
this.report.push(this.report.length)
}
The form array was working, but i want to know how the value should be different than the other select.
And the result that i hope works is :
Should be like add new form array, but the value in it can be changed.
Although what you are asking is not very clear. but a possible problem which I see is with [ngValue]. You could try using [value] instead.
<option [value]="item.name" *ngFor="let item of listProjects">
{{item.name}}
</option>

Populate a select with ajax with ng-options using AngularJs

With angularJS, I need populate a select with data coming from a ajax call.
I have a controlller called "TabPacProfissionalController".In this controller I do a ajax call to get json data('profissionais object').
So far so good.
My problem is that I get the json data returning from server, but my select is never populate.
What am I missing here?
My ajax return is:
{"results":[{"nr":"8","nome":"AAAAAAAAAAAA"},
{"nr":"17","nome":"BBBBBBB"},
{"nr":"27","nome":"BBBBBAAAAA"},
,{"nr":"1004","nome":"CCCCCCCCC"}]}
HTML
<div class="form-group">
<label for="paciente.texto.sexo" class="col-sm-2 control-label">Profissional:</label>
<div class="col-sm-10" ng-controller="TabPacProfissionalController as tabProfCtrl">
<select class="form-control" ng-model="selectedProf" ng-options="nome for (nr,nome) in tabProfCtrl.profissionais">
<option value=''>Select an option</option>
</select>
</div>
</div>
JS:
app.controller('TabPacProfissionalController', function($http) {
this.profissionais = {};
$http.get('/getStaff?tipoProf=1').then(function(response){
this.profissionais=response.data.results;
console.log(this.profissionais.toString());
},function(error){
console.log(error);
});
});
If you want the label to display the nome property and the value to be the nr property try the following:
<div class="form-group">
<label for="paciente.texto.sexo" class="col-sm-2 control-label">Profissional:</label>
<div class="col-sm-10" ng-controller="TabPacProfissionalController as tabProfCtrl">
<select ng-model="tabProfCtrl.selectedProf" ng-options="profissionais.nr as profissionais.nome for profissionais in tabProfCtrl.profissionais">
<option value="">Select</option>
</select>
</div>
</div>
(key,value) notation you are using is for object data sources, as in if you wanted to iterate through the properties of a single object, rather than a collection of objects which is what you seem to be getting from the $http call.
To see the parsed server response, you could use angular.fromJson(response.data)
Here is a plunker demonstrating the functionality.

Angular Empty option (Dynamic input)

Been searching all over Stackoverflow and there is loads of tips on how to remove the 'dreaded' empty (undefined) options element in a select dropdown. However I have yet to find an answer for when my code looks like this:
--VIEW--
<form class="simple-mods">
<fieldset ng-repeat="modifier in modifiers">
<label for="{{ modifier.id }}">{{ modifier.title }}</label>
<select name="" id="{{ modifier.id }}" ng-model="mods[modifier.id]" name="modifier[{{ modifier.id }}]" ng-mod="{{ modifier.title }}">
<option value="{{ variation.id }}" ng-repeat="variation in modifier.variations">{{ variation.title }}</option>
</select>
</fieldset>
<fieldset>
<button ng-click="addCart()" ng-if="!addStatus" class="btn btn-success" translate>Add to cart</button>
<button ng-if="addStatus" class="btn btn-warning" ng-bind-html="addStatus">{{ addStatus }}</button>
</fieldset>
</form>
-- CONTROLLER --
.controller('ProductCtrl', function ($scope, $rootScope, moltin, $timeout, product) {
var productId = product.id,
qty = 1,
mods = {};
$scope.product = product;
$scope.addStatus = null;
$scope.modifiers = product.modifiers;
});
If any one can help I would be very grateful.
#BETTY it doesnt seem to work. I have attached 2 screenshots
Screen shot 3
Screen shot 4 (Value is now a string)
#betty
<fieldset ng-repeat="modifier in modifiers" ng-init="mod[modifier.id] = modifier.variations[0].id">
<label for="{{ modifier.id }}">{{ modifier.title }}</label>
<select id="{{ modifier.id }}" ng-model="mods[modifier.id]" ng-options="variation.id as variation.title for variation in modifier.variations">
<option></option>
</select>
</fieldset>
Try to clean up modifier.variations in your controller, deleting undefined elements from modifier.variations
$scope.modifier.variations = $scope.modifier.variations.filter(function(n){ return n != undefined });
You need to inject $scope in your controller.
You need to set the ng-model right (=> mods[modifier.id]), either by using ng-init or setting it in the controller..
This solution uses ng-init which sets the default value to the first variation ID. I also removed everything you don't need and used ng-options (reduces some HTML ;)).
<fieldset ng-repeat="modifier in modifiers" ng-init="mods[modifier.id]=modifier.variations[0].id">
<label for="{{ modifier.id }}">{{ modifier.title }}</label>
<select id="{{ modifier.id }}" ng-model="mods[modifier.id]" ng-options="variation.id as variation.title for variation in modifier.variations">
<option></option>
</select>
</fieldset>
I also recommend adding an empty option-tag, here is why: ng-model is getting wrong value from dropdown
AND you need $scope.mods = {}; in the controller instead of var mods = {}; because you are using mods in the HTML!
Maybe you also need to use track by variation.id so that the selected value can be checked right (ng-model and option value). I answered a similar question and track by was the answer, see https://stackoverflow.com/a/32999399/595152 ;)

AngularJS select in ng-repeat

I am creating a list of <select>'s with ng-repeat, there is a item.quantity that I need to be selected in each select in the list, I have tried several ways without success. Any help would be appreciated.
<div ng-repeat="item in items">
<select ng-model="selCartQuantity">
<option index="1" ng-selected="item.quantity=='1'">1</option>
<option index="2" ng-selected="item.quantity=='2'">2</option>
<option index="3" ng-selected="item.quantity=='3'">3</option>
<option index="4" ng-selected="item.quantity=='4'">4</option>
<option index="5" ng-selected="item.quantity=='5'">5</option>
</select>
</div>
in your controller you put the following code (of course you change $scope.items to your actual object )
$scope.items = [{name:'aaaaa'},{name:'bbbbb'}];
$scope.options= [1,2,3,4,5];
$scope.items.forEach(function(item,index){
item.selCartQuantity= $scope.options[0];
});
and in the html markup you put the following
<div ng-repeat="item in items">
<select ng-model="item.selCartQuantity" ng-options="option for option in options"></select>
</div>
`
I would reccomend checking out the angular select driective, as you shouldn't have to do the ng-repeat at all. The select directive will automatically set the selected option to be what you have in your model.

Perform orderBy when dropdown is selected angularjs

I have a drop down list consisting of name and address. if name is selected then my list should be sorted with name.
My code is not working properly` Order By
<div class="col-xs-2">
<select class="form-control" ng-change="changedvalue()" ng-model="Tosort.order">
<option value="None">-- Select --</option>
<option ng-model="Tosort.order" value="Name">Name</option>
<option ng-model="Tosort.order" value="Address">Address</option>
</select>
</div>
<li ng-repeat="x in details | filter: Tofilter.country | orderBy:sort.value">
You need to simply use ng-model instead of the ng-change() event. There are some other issues in your code as well like you need to provide ng-model only on the select tag. I think you may need to revisit some angular basics. I've shown how it could work below. the select tag will be bound to "sortBy" and the same is used in the "orderBy" filter
<div class="col-xs-2">
<select class="form-control" ng-model="sortBy">
<option value="None">-- Select --</option>
<option value="Name">Name</option>
<option value="Address">Address</option>
</select>
</div>
<li ng-repeat="x in details | filter: Tofilter.country | orderBy:sortBy">
I see you got lot's of answers while I was still writing my example. Damn you're fast! :)
Anyway, this would be content of your HTML
<body ng-controller="MyCtrl">
<div>
<!-- text input for filtering -->
<label>Country filter</label>
<input type="text" ng-model="countryFilter"></input>
<!-- options to order (filtered) results -->
<label>Order by</label>
<select ng-model="selectedOrder" ng-options="option for option in options"></select>
</div>
<ul>
<!-- show results: filter by country name and order by selected property name -->
<li ng-repeat="detail in details | filter:{country: countryFilter} | orderBy:selectedOrder">{{ detail }}</li>
</ul>
</body>
And this would be related controller
var app = angular.module('plunker', []);
app.controller('MyCtrl', function($scope) {
// order by options
$scope.options = ['country', 'address'];
// all countries
$scope.details = [{
id:1, country:'Country 1', address:'Address C'
},{
id:2, country:'Country 2', address:'Address B'
},{
id:3, country:'Country 3', address:'Address A'
}];
});
For future reference, working plunker here http://plnkr.co/edit/02Y3b7

Resources