set value to select angularjs - javascript

MEDService.users("GET", "", {"action" : "getUsers"})
.success(function(data, status, headers, config) {
$scope.data1 = data;
have this code, how i can set this item(get from mongo) in select on front end?
data1 have fields: username, name, password. I need just username
<select ng-model="??" style="display: block" >
<option ng-selected="??"
ng-repeat="??"
value="???">
???
</option>
</select>

Assuming that your data1 looks like
data1 = [
{name:'Real Name1', username:'username1', password: 'secret'},
{name:'Real Name2', username:'username2', password: 'secret'},
{name:'Real Name3', username:'username3', password: 'secret'}
]
try
<select ng-model="selectedUser" ng-options="user.name for user in data1"></select>
The selected user will be stored in selectedUser, you can easily validate that by using
<h2>{{selectedUser}}</h2>
in your html.
Working example: http://plnkr.co/edit/pggWiNO0TpIlCLOlFtzW

You must create another property on your scope, like selectedValue and then use this markup :
<select ng-model="$scope.selectedValue">
<option ng-repeat="option in $scope.data1" value="{{option.id}}">{{option.name}}</option>
</select>

As I understand you have something like that:
$scope.data1 = [
{username: 'olga', name: 'Olga K', password: 'querty'},
....
];
As the result you are going to receive username in this case it's olga value.
I see two solution you can do
First solution for string array you may prepare your date to view.
$scope.data1 = $scope.data1.map(item => item.username);
Then your html may look like that
<select ng-model="SELECTED_PROPERTY" ng-options="o as o for o in data1"></select>
Second soultion
when you have object array
<select ng-model="SELECTED_PROPERTY" ng-options="o.username as o.name for o in data1"></select>
NOTE: if you never use other object properties first solution is better one cause use few RAM memory.

Related

422 HTTP Error with picker-input form in vue.js

I have a file upload form built with vue.js. The input data is packed into JSON and sent to the backend. Normally, this works successfully, I can retrieve the POSTed JSON objects with GET.
Problems arise after implementing a picker input for the file type:
<select class="home-select dataform dataselect" v-model="file_type">
<option disabled value="">Select dataset type</option>
<option v-for="type in allowedFileTypes" :value="type" :key="type.id">{{ type }}</option>
</select>
The allowed file types are defined in a list in data() as either Indicator Matrix or Expression Matrix.
I also have a text input field for the name of the dataset.
The Problem
I get a 422 error when I leave fields empty.
I get a 422 error when I select "Expression Matrix" and fill everything else.
I DON'T get a 422 error when I select "Indicator Matrix" and fill everything else.
Why does this happen and how can I fix this? I also want to be able to leave fields empty.
The total vue component looks like this:
<template>
<div class="container">
<h1>Showcase Page</h1>
<select class="home-select dataform dataselect" v-model="file_type">
<option disabled value="">Select dataset type</option>
<option v-for="type in allowedFileTypes" :value="type" :key="type.id">{{ type }}</option>
</select>
<input type="text" placeholder="Enter dataset name" class="input dataform" v-model="name"/>
<button class="btn btn-default" type="button" #click="uploadFile">Upload</button>
</div>
</template>
<script>
export default {
name: 'test',
props: {},
components: {},
methods: {
async uploadFile() {
const response = await fetch(`${this.BASE_URL}/dataset`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: this.name,
type: this.file_type
})
})
console.log("response:")
console.log(response)
const blob = await response.blob();
console.log(blob)
}
},
data() {
return {
file: new File([""], "file"),
name: "",
file_type: "",
allowedFileTypes: ["Indicator Matrix", "Expression Matrix"],
BASE_URL: process.env.VUE_APP_SERVER_URL
}
}
}
</script>
I logged the values of the variables as well as their type with .type and typeof.
.type always gives undefined
typeof always gives string
What does it mean that .type is always undefined, even when the input of the variable is filled?
I found the root of the problem:
Thanks to Bravo I looked into the server. That the problem lies there is of course also indicated by the 422 error. I use grails and the constraints of the File domain class are probably the reason of the errors.
I made the fields nullable and "blankable", which solved the issue.

Vue, building a select list out of array of options but pre-selecting based on async response

I've been trying to test out a way in vue to build a select list with a hardcoded array of options, however, if a certain async response/event comes in with an assignee attached, I am setting that as 'currentAssignee' which is my preselected option.
This kind of works, but it initially looks empty/invisible. If I click the seemingly non-existent select box, the options will show 'Name One', 'Name Two' and 'John Doe' which is the name from the response. But it doesn't actually satisfy the 'selected' option because it is essentially invisible to the user on page load, until it's clicked
Should I be doing something different?
<select class="firstLastNames linkBox" v-model="currentAssignee" #change="changeAssignee()" >
<option :selected="true">{{currentAssigneeFirst}} {{currentAssigneeLast}}</option>
<option v-for="assignee in assigneeOptions" >{{assignee.email}}</option>
</select>
data () {
return {
currentAssignee: '',
assigneeOptions: [
{id: 0, email: "Name one"},
{id: 1, email: "Name two"}
],
},
}
/**further down, I set currentAssignee based on async event**/
this.currentAssignee = triggerEvent[0].assignee;
I put a code sample together here which I think fixes your issue:
https://codepen.io/timfranklin/pen/bGWYggG
Take a look at what is being bound by the v-model. The "value" of a select is not the object itself, it's some value of an object.
<select class="firstLastNames linkBox" v-model="currentAssignee" #change="changeAssignee($event)" >
<option disabled >Choose One</option>
<option v-for="assignee in assigneeOptions" :key="assignee.id" :value="assignee.id">{{assignee.email}}</option>
</select>
The important note here is the :value="assignee.id";

ng-show on array of objects on select dropdown with ng-options

I am using the ng-options to iterate over my array of objects and display the proper list of statuses to the view as well as bind what i need to the model.
There are two states that this view can be in at any given time and one is an empty workOrder or a workOrder that already has values.
Now i would like in the instance that a workOrder has returned with a status of 'A' or an 'Active' status, the 'Closed' and 'Processing' statuses will not display in the dropdown.
I would like to use ng-show for this but would also like to know if there is a more appropriate method of going about solving this.
my objects:
workOrder.statuses = [
{
'Status': 'Open',
'Code': 'O',
'Show': true
},
{
'Status': 'Active',
'Code': 'A',
'Show': true
},
{
'Status': 'Processing',
'Code': 'P',
'Show': true
},
{
'Status': 'Closed',
'Code': 'C',
'Show': true
}
];
my HTML on which i am using:
<select title="Status" class="form-control" id="ddlStatus"
ng-options="status.Code as status.Status for status in ctrl.statuses"
ng-model="ctrl.model.Status">
</select>
I am running into issues on trying to get this to work and nothing seems to work and searching through StackOverflow i was unable to find a solid answer.
Any help is much appreciated!
First of all, you can just filter your options array like this:
<li ng-repeat="status.Code as status.Status for status in ctrl.statuses | filter : {Status: 'Open'}: true">
Second of all, you can populate select with the options like this
<select name="repeatSelect" id="repeatSelect" ng-model="data.repeatSelect">
<option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
</select>
So you can specify there with 'ng-if' to hide the options with status you don't want to show
Update:
So you can use filter:
<option ng-repeat="status in ctrl.statuses | filter : {Status: '!' + ctrl.model.Status}: true" value='{{status.Code}}'>{{status.Status}}</option>
Or if you don't want to use ng-repeat, you can just filter the options array in the scope when the selected status is changed.

Angular changing dataset without $watch

I have an array of objects like this
UserList = [
{name:'user1',id:1,data:{}},
{name:'user4',id:4,data:{}},
{name:'user7',id:7,data:{}}
]
And html select like this
<select ng-model="data.selectedUser">
<option ng-repeat="item in data.items" value="{{item.id}}">{{item.name}}</option>
</select>
<p>{{data.userPhone}}</p>
Inside my controller I use
$scope.data = {};
$scope.data.selectedUser = 0;
$scope.data.items = UserListModel.items;
$scope.data.userPhone = UserListModel.items[$scope.data.selectedUser].phone;
Is there a way to update selected user phone on selectedUser change without using $watch and stuffing the "$scope.data.userPhone" inside it?
Imagine you have a data like this:
$scope.data = {};
//set the data
$scope.data= [{
id: 1,
name: "cyril",
phone: "1234567"
}, {
id: 2,
name: "josh",
phone: "1237"
}, {
id: 3,
name: "sim",
phone: "4567"
}];
//selected hold the object that is selected in the selectbox.
$scope.selected = $scope.data[0];
Your html will look like this below so now when you select the new user from the list it will be updated in the model selectedItem, the selectedItem has the phone number in it (so you dont need a watch to update phone number seperately as you doing).
<body ng-controller="MainCtrl">
<p>selected item is : {{selectedItem}}</p>
<p> name of selected item is : {{selectedItem.name}} </p>
<select ng-model="selectedItem" ng-options="item.name for item in items track by item.id"></select>
</body>
working example here
One possibility would be to have
$scope.data.userPhone = function () {
return UserListModel.items[$scope.data.selectedUser].phone;
}
This would mean though that you'd have to update any bindings to use data.userPhone() instead.
This might be worse than using a watch though, as the function would get called during every digest.
Without knowing how selectedUser gets updated it's difficult to suggest a best way as, with most things, it depends.

How do i store an array of objects with angularJS

i have this schema of a object in mongoDB, i will call my object CAR in this question:
this.carroSchema = new Schema({
modelo: String,
ano: String,
placa: String,
cor: String,
categoria: [{tipo: String, preco: String}],
createdOn: {type: Date, default: Date.now}
});
and i have this function that gets the object CAR and stores in the array 'arrayCarros'
$scope.carregarCarros = function(){
$http({
method: 'GET',
url: '/listaCarro'
})
.then(function successCallback(response){
$scope.arrayCarros = response.data;
}, function errorCallback(response){
alert(response.data);
});
}
if i do a select like this:
<select class="form-control" ng-click = "carregarCarros()" name="select">
<option ng-repeat = "carros in arrayCarros">{{carros.placa}}</option>
</select>
i have access to the propertie 'placa' from the object CAR, so i can show the values in my select.
but, my question is, how do i store the array 'categoria' that is inside of my object CAR, in other array so i can do a ng-repeat of him in my option and have access of his properties like 'tipo' and 'preco'?
Here is a simple way to do it. Obviously you could always use a built in javascript function like Array.filter or Array.reduce depending on your use case, but below is a simple to follow solution.
$scope.other_array = [];
response.data.forEach(function(car){
$scope.other_array.push(car.categoria)
})
console.log(other_array)
It should also be noted you can have multiple ng-repeats and just have one render carros.place and one render carros.categoria. That or just have both vars rendered within the same ng-repeat.

Categories