Problems loading content dynamically in a SELECT FIELD [ANGULAR JS] - javascript

Hello thanks for help me. I have two select field, one select field for states, and other select for the cities. I am trying to load cities dinamically from the JSON generated in the server, when the user change the selected state.If you can help, many thanks..
JavaScript:
var geo = function(app){
app.controller("geoCtrl",function($scope, $http, geoFactory){
$scope.mcpios = [];
$scope.dptos = [];
$scope.$watch('dpto', function (nuevoValor, viejoValor) {
if(!viejoValor || !nuevoValor) return;
if (nuevoValor.id_departamento === viejoValor.id_departamento) { return; }
geoFactory.actMucpios($scope.dpto.id_departamento).success(function(rs){
console.log(rs[0]);
$scope.mcpios = rs[0];
});
}, true);
geoFactory.get().success( function(rs){
$scope.dptos = rs[1];
$scope.dpto = $scope.dptos[0];
});
});
app.factory("geoFactory", function($http){
var factory = {};
factory.get = function(){
return $http.get("aplicacion/controladores/controlador_geo.php?listar");
};
factory.actMucpios = function(id_dpto){
return $http.get("aplicacion/controladores/controlador_geo.php?listar&id_dpto=" + id_dpto);
}
return factory;
});
}
HTML:
<select ng-controller="geoCtrl" ng-change="actulizar()" ng-model="dpto" class="col-md-12" ng-options="dpto.nombre for dpto in dptos" >
<option ng-repeat-start>Seleccione un Departamento</option>
<option value="{{dpto.id_departamento}}" ng-repeat="dpto in dptos">{{dpto.nombre}}</option>
</select>
<select ng-model="mcpio" class="col-md-12" ng-controller="geoCtrl">
<option ng-repeat-start>Seleccione una Ciudad</option>
<option value="{{mcpio.id}}" ng-repeat="mcpio in mcpios | filter:dpto.id">{{mcpio.nombre}}</option>
</select>
I hope that you can help me... Thanks

I create the plunkr below that simulates making a call to a service to retrieve a list of states. Then when a state is selected it will retrieve from the object (or if you need you could request the list of states in the $scope.watch statement to retrieve the cities then set the list of cities to scope collection for the cities and each time you select a new state the list of cities will change.
Here's a link to see the working example : http://plnkr.co/edit/ntUblVSSoBzp053GuYvv?p=preview

Related

Create multiple dynamic select filters based on an array with unique values to filter another array in Vue.js

I am currently new to Vue.js and this is my first question on stack so forgive me if I am not the most clear.
I am trying to create multiple dynamic select filters to filter a list that I have gotten from an api using axios.
I have surfaced the data within my HTML template and have managed to create the two filters, my main issue is that I need the filters to only display unique values (no duplicates) and this is where I am struggling.
This is mainly a proof of concept for work which displays a group of users names, there label and position. We where using angularjs before and are now looking to move over to Vue.js, so I haven't gotten to grips with it yet, and currently stumped as I don't understand how to make the information from one source data array filter another source data array.
Here is what I have currently in my app.js
new Vue({
el: "#vueApp",
data: {
users: [],
JobRole: '',
Label: '',
search: '',
JobRoles: [],
},
created: function() {
this.getResults();
},
methods: {
getResults: function() {
var vm = this;
axios.get("APIData").then(function(response) {
console.log(response.data.value);
vm.users = response.data.value;
})
},
filterPosition:function() {
var vm = this;
vm.item.Position = event.target.value;
},
filterLabel:function() {
var vm = this;
vm.item.Meta.Label = event.target.value;
}
},
computed: {
JobRoleList: function(){
var vm = this;
var JobRoles = [];
vm.users.forEach(function(item){
if(!JobRoles.includes(item.Position)){
JobRoles.push(item.Position);
console.log(JobRoles);
}
});
return JobRoles;
},
filterAll: function(){
var vm = this;
var filtered = vm.users;
// var JobRoles = vm.JobRoles;
if (vm.search) {
filtered = vm.users.filter(function(item){
return item.People.Title.indexOf(vm.search) > -1
});
}
if (vm.Label) {
filtered = filtered.filter(function(item){
return item.Meta.Label.match(vm.Label)
});
}
if (vm.JobRole) {
vm.JobRole = filtered.filter(function(item){
return item.Position.match(vm.JobRole)
console.log(JobRole);
});
}
return filtered
console.log(filtered);
},
}
});
Here is my Markup
<div id="vueApp">
<div>
<select v-model="JobRole">
<option value="">Select a Position</option>
<option v-for="item in JobRoleList" :value="item.Position">{{item}}</option>
</select>
<select v-model="Label">
<option value="">Select a Label</option>
<option v-for="item in filterAll" :value="item.Meta.Label">{{item.Meta.Label}}</option>
</select>
<input type="text" v-model="search" placeholder="Search...">
<table>
<tr>
<th>Name</th>
<th>Department</th>
<th>Position</th>
<!-- <th>People Title</th> -->
</tr>
<tr v-for="item in filterAll">
<td>{{item.People.Title}}</td>
<td>{{item.Meta.Label}}</td>
<td>{{item.Position}}</td>
</tr>
</table>
</div>
</div>
So what I want to get to is have each filter to have unique values with no duplication and to filter the information within the list.
I have managed to create a unique value array for one of the select filters under JobRoleList, I just need to know how to have it communicate with the filterAll array, if I can get to that stage then all I would need to do is replicate that for the other filter.
I would appreciate any help and would be more than happy to provide more detail.
There are a few problems with your code:
You're binding the wrong value to the job role select. Right now your code says :value="item.Position" when the JobRoleList variable is an array of strings. So when you click select there won't be a value for JobRole
<select v-model="JobRole">
<option value="">Select a Position</option>
<option v-for="item in JobRoleList" :value="item.Position">{{item}}</option>
</select>
You're filtering the wrong variable in your filterAll computed variable in the jobRole part
if (vm.JobRole) {
vm.JobRole = filtered.filter(function(item){
return item.Position.match(vm.JobRole)
console.log(JobRole);
});
// This should say "filtered =" not "vm.JobRole ="
}
There's also a much more succinct way to get a unique list of values using ES6:
JobRoleList: function({ users }) {
return [...new Set(users.map(d => d.Position))];
}
You can also make your search all lower case letters before matching to improve the user experience.
filtered = users.filter(function(item){
return item.People.Title.toLowerCase().indexOf(search.toLowerCase()) > -1
});
I've made a codepen with a working demo: https://codepen.io/CodingDeer/pen/abomBXP

Getting blank dropdown value even after using ng-selected

I am using ng-selected to get the selected value from a dropdown. But instead it's showing as blank.
I have tried the following code:
<div>
<select id="user_org" ng-model="selectedorg.allValue" ng-change="qrochange(this)" material-select watch required >
<option ng-selected='{{selectedorg.allValue == user.user_org}}' ng-repeat="user in orgowners | unique:'user_org'" value="{{user.id}},{{user.user_org_quota}}">{{user.user_org}}</option>
</select>
<label for="user_org">Organization</label>
</div>
Controller.js:
var orgowners = Restangular.one("users/" + user_id + "/list");
orgowners.getList().then(function(projects) {
$scope.orgowners = projects;
var parent_index = $scope.findIndexByKeyValue($scope.orgowners,'id',$scope.id);
$scope.selectedorg= $scope.orgowners[parent_index];
$scope.selectedorg.allValue = $scope.selectedorg.id+','+$scope.selectedorg.user_org_quota;
$scope.qro = $scope.selectedorg.user_org_quota;
})
$scope.qrochange = function(event) {
id = event.selectedorg.allValue;
var quota_res = id.split(',')[1];
$scope.qro = quota_res;
$scope.user_org_quota = parseInt(quota_res);
}
How do I get the selected value?
ng-model should give the selected value.
An easier way to render the dropdown is using ng-options. Something like:
<select ng-model="selectedorg" ng-options="user.user_org for user in orgowners | unique:'user_org'">
See also: angularjs ngOptions

How to set a particular value selected when data is coming from an API

I have a dropdown list:-
<label>User Code:</label>
<select ng-options="c as c.User for c in userList"
ng-model="selectedUser" id="search3">
</select>
The data in this dropdown is coming from an API. My directive code:-
scope.getAllPeriodicities = function(){
scope.userList = [];
ApiServices.getAllPeriodicities().then(function (response) {
scope.userList = response.data;
});
}
scope.getAllPeriodicities();
There is an User Code:-SS1234. I want this user to be selected whenever the page loads. I am thinking of using selected attribute but not sure how to use it on the fetched data.
scope.getAllPeriodicities = function(){
scope.userList = [];
ApiServices.getAllPeriodicities().then(function (response) {
scope.userList = response.data;
scope.selectedUser = "SS1234";
});
}
scope.getAllPeriodicities();
simply asign, scope.selectedUser="SS1234" user you want.
scope.userList = response.data;
scope.selectedUser = scope.userList[0].User /* here i choose 0th index of user. you can change as you want */
Set your default value to the ng-model by using ng-init or ng-value
<select ng-options="c as c.User for c in userList" ng-model="selectedUser"
id="search3" ng-value={{selectedUser = 'SS1234'}}></select>
//or
<select ng-options="c as c.User for c in userList" ng-model="selectedUser"
id="search3" ng-init="selectedUser = 'SS1234'"></select>
In your controller add,
$scope.selectedUser = 'SS1234';

How to `update` new value choosing from `select box` on click save button?

How to update new value choosing from select box on click save button.
I am using ng-click function like this in my JS function for update button:
$scope.updateDealDetail = function updateDealDetail (){
$scope.showEditView = !$scope.showEditView;
$scope.dealDetail.decisionMakerDetail.email = $scope.selectedid;
}
My function for edit button:
$scope.editUserDetail = function editUserDetail(){
$scope.showEditView = !$scope.showEditView;
$scope.showSubmitView = !$scope.showSubmitView;
deal.getIdData($scope.accountDetail. accountUsers[0].role,$scope.accountDetail.id).then(function successCb(data){
$scope.editIdOptionsData=data;
$scope.selectedid = $scope.editIdOptionsData[0].email;
});
};
and my HTML for bitton click is like this :
<select ng-model="selectedid" class="form-control">
<option ng-selected="selectedid" ng-repeat="eiod in editIdOptionsData" value="{{eiod.email}}">{{eiod.email}}
<button ng-click="updateDealDetail(eoid.email)" ng-disabled="dealDataSaveButtonDisabled">Update</button>
I am trying to this through ng-repeat because of by using ng-options my data through API is now showing in the box. But My data which is on first index is only getting set. What to do to set the a default value for the selection box and by selection any value, onclick need to update that value.
Don't use ngRepeat to render options, this is your problem. Correct code would be:
<select class="form-control"
ng-model="selectedid"
ng-options="eiod.email as eiod.email for eiod in editIdOptionsData">
</select>
Best practice to use ng-options, ng-model and ng-change on the <select> element
Online demo - https://plnkr.co/edit/Gaa8sMgerRv6chio4iYa?p=preview
html
<select
ng-model="selectedItem"
ng-change="onSelectedItemChanged()"
ng-options="item as item.email for item in items"></select>
js
app.controller('MainCtrl', function($scope) {
$scope.items = [{
email: 'asd1#asd.com'
}, {
email: 'asd2#asd.com'
}];
$scope.selectedItem = $scope.items[0];
$scope.onSelectedItemChanged = function() {
alert('you changed it to ' + $scope.selectedItem.email);
}
});

How do I get ng-select to update when scope is changed?

I have a table above a form, that when a row is selected it populates a form with data. That form has a select element. Upon the first row in the table being selected, the data populates correctly and the correct selected option is shown. On the second and subsequent selection the correct selected option is not shown. In chrome dev tools I can see the values update properly, but it is not visually shown.
What am I missing? How do I get that correct option to be visually shown?
<select name="updateCategory" ng-model="selectedPermission.permission.category_id">
<option value="{{cat.id}}" ng-selected="cat.selected" ng-repeat="cat in selectedPermission.permission_categories">
{{cat.name}}
</option>
</select>
Here is function in controller that is updating the scope.
$rootScope.$watch('toolBarSelectedValue',function(){
if($rootScope.toolBarSelectedValue >0){
Permissions.getItem($rootScope.toolBarSelectedValue).then(function(res){
var pc = res.data.permission_categories;
var p = res.data.permission;
angular.forEach(pc,function(v,k){
if(v.id == p.category_id){
pc[k].selected = true;
}else{
pc[k].selected = false;
}
});
$scope.selectedPermission = {"permission":p,"permission_categories":pc};
$scope.$apply();
});
}else if($rootScope.toolBarSelectedValue == 0 || $rootScope.toolBarSelectedValue == null){
$scope.selectedPermission = {};
}
});
I would use ng-options as opposed to <option...></option> you can then relate your selection to your ng-model easily. See docs for more info.
Something like:
<select name="updateCategory" ng-model="cat" ng-options="cat.id as cat.name for cat in selectedPermission.permission_categories">
</select>
bear in mind I am not sure of you data structure, but this should get you on your way.

Categories