AngularJS Dynamically Creating Select Box - ngModel Not Registering - javascript

I am using one select box to conditionally generate a second select box. The select boxes populate correctly and everything looks okay in the Chrome Inspector on the elements.
The problem is the ng-model (ng-model="commandName" in the code example below) does not properly register the correct select value. So, if you look in the example, the {{commandName}} output at the end correctly outputs for the first select box but for the second select box nothing is output.
Is this a bug? Can anyone recommend an alternate method for approaching this problem?
Everything appears to work except commandName does not output anything in the p tag at the bottom but commandType does.
<select ng-model="commandType" class="form-control" ng-init="commandType = ''; command = ''">
<option value=""></option>
<option ng-repeat="commandGroup in commandList" value="{{$index}}">{{commandGroup.name}}</option>
</select>
<!-- Shown if something is selected in the select box above -->
<select ng-model="commandName" class="form-control" ng-if="commandType !== ''">
<option value=""></option>
<option ng-repeat="exactCommand in commandList[commandType].commands" value="{{$index}}">{{exactCommand.name}}</option>
</select>
<p>{{commandName}}</p>
AngularJS code:
$scope.initCommandList = function () {
$http({
method: 'GET',
url: $rootScope.webserver + 'admin/rterminalCommandList/',
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data) {
console.log("Command list");
console.log(data.data);
$scope.commandList = data.data;
});
};
$scope.initCommandList();
And POST response:
{
"data"
:
[{
"id": 2,
"name": "Application",
"commands": [{
"id": 3,
"name": "Delete Smartcare data",
"syntax": "su -c pm clear com.patasonic.android.smartcare",
"comment": "Deletes Smartapp data"
}]
}, {
"id": 1,
"name": "Bluetooth",
"commands": [{
"id": 2,
"name": "Bluetooth Controls. Turn off",
"syntax": "bluetooth# off",
"comment": "Turns off device bluetooth"
}, {"id": 1, "name": "Bluetooth Controls. Turn on", "syntax": "bluetooth# on", "comment": "Turn on bluetooth"}]
}], "header"
:
{
"messages"
:
[], "response_code"
:
200
}
}

I recommend you to use "select ng-options" instead of "option ng-repeat"
https://docs.angularjs.org/api/ng/directive/ngOptions
<select ng-model="myModel"
ng-options="command as command.name for command in commandList">
</select>
Here is a jsfiddle with an example:
http://jsfiddle.net/jcamelis/5y086ytr/4/
I hope it helps.

Related

Trouble getting label from array instead of value

So I am using an array to populate a dropdown menu and right now that part works great. I use the value to help calculate service cost and i use the label to display the option name to the user. My issue now is that my form is sending the value(which is just the price) and not the label. I may need it to do both potentially if my paypal button is my submit button? im not sure. Right now i just have the form sending to discord though.
HTML for particular selection menu
<fieldset>
<label for="rank-tourn">
Select Tournament Title
</label>
<select id="rank-tourn" name="Desired Tournament Rank" class="menus form-select" onchange="onChangeCurrent()">
<option value="0" label="" >Select</option>
</select>
</fieldset>
java for populating list
function buildOptList(select, id) {
select.innerHTML = null;
//alert("Populate list");
for (var i = id; i < Rankings.length; i++) {
if ((id == 0) && (i == Rankings.length)) {
// do nothing
} else {
var el = document.createElement("option");
el.textContent = Rankings[i].label;
el.value = Rankings[i].value;
select.appendChild(el);
}
}
}
My array
var Rankings = [{
"id": 1,
"value": 10,
"label": "Bronze Title",
}, {
"id": 2,
"value": 10,
"label": "Silver Title",
}, {
"id": 3,
"value": 15,
"label": "Gold Title",
}, {
"id": 4,
"value": 20,
"label": "Platinum Title",
}, {
"id": 5,
"value": 25,
"label": "Diamond Title",
}, {
"id": 6,
"value": 30,
"label": "Champion Title",
}, {
"id": 7,
"value": 40,
"label": "Grand Champion Title",
}, {
"id": 8,
"value": 80,
"label": "Supersonic Legend Title",
}];
I have also tried using jquery to try and copy the selection label to a hidden field but im having trouble with that too.
This was my attempted jquery:
HTML
<input type='hidden' id='hidden' value='0' label=''/>
JQUERY
$("#rank-tourn").change(function () {
$("#hidden").text($(this).text());
alert($(this).text())
})
currently this alerts on change everysingle label together. I have tried adding the :selected to rank-tourn and then it fails to alert.
https://jsfiddle.net/Popo74123/q92jh1p0/465/ this is my code if its easier.
this.text() will get the value of everything, you need to find the pseudo selector :selected to display the one that was chosen
$("#rank-tourn").change(function () {
$("#hidden").text($(this).find(':selected').text());
alert($(this).find(':selected').text())
})
Just remove this line:
el.value = Rankings[i].value;
when an option doesn't have an explicit value, it's text becomes the value.

Semantic UI dropdown lists displays 'undefined'

I'm having difficultly getting a Semantic UI (v2.4.2) dropdown to work as expected.
If I click the down arrow, the dropdown displays a list of undefined items:
If I type the name of a tag, the dropdown displays the correct list of tags:
HTML:
<div id="myList" class="ui multiple search selection dropdown">
<input type="hidden" name="tags">
<i class="dropdown icon"></i>
<div class="default text">Tags</div>
</div>
<script type="text/javascript">
$("#myList").dropdown({
minCharacters : 3,
allowAdditons : true,
apiSettings : {
url : '//localhost:9393/tags/search?q={query}',
onResponse: function(tags) {
console.debug('onResponse');
var response = {
success: true,
results: []
};
$.each(tags, function(index, item) {
response.results.push({
name: item.name,
value: item.id
});
});
return response;
}
}
});
</script>
The JSON API returns a list of tags as an array:
[
{
"id": 5,
"name": "mssql",
"description": "Microsoft SQL Server is a relational, database-management system developed by [Microsoft](https://www.microsoft.com/)."
},
{
"id": 6,
"name": "oracle",
"description": "Oracle's DBMS"
},
{
"id": 8,
"name": "plsql",
"description": "[PL/SQL](https://en.wikipedia.org/wiki/PL/SQL) is Oracle Corporation's procedural extension for SQL and the Oracle relational database."
}
]
Oddly, the onResponse callback only fires when a value is typed in the search box.
What am I missing?
you've set the minimum number of characters to initiate the search to 3 right here:
$("#myList").dropdown({
minCharacters : 3,
allowAdditons : true
simply add:
showOnFocus:true
to your configuration object. It should solve the problem.

How to show the selected plan value in a text box in vue js html?

My json data is as follows
{"status": true, "plans": [{"planId": 1, "name": "Baic", "cost": 500.0, "validity": 365}, {"planId": 3, "name": "free", "cost": 0.0, "validity": 999}, {"planId": 4, "name": "Premium", "cost": 500.0, "validity": 500}, {"planId": 5, "name": "Super Premium", "cost": 750.0, "validity": 600}, {"planId": 6, "name": "New", "cost": 600.0, "validity": 180}]}
I need to select a particular category from the above list and display the corresponding cost of the category in a text box and i need to able to edit the value. How acan I able to obtain the same.
Currently my html code is
<div class="form-group">
<label>Plan <small>(select your plan)</small></label>
<select id="bas" class="selectpicker" data-live-search="true" data-live-search-style="begins" title="Select Plan" v-model="plan" name="plan" ref="plan" required="required">
<option v-for="post in plansb" v-bind:value="post.planId" v-if="plansb.indexOf(post) > 0">{{post.name}} (Rs.{{post.cost}})</option>
</select>
</div>
<div class="form-group">
<label>Plan Amount <small>(required)</small></label>
<input name="plan_amt" type="text" class="form-control" id="plan_amt" placeholder="Plan Amount" v-model="plan_amt" />
</div>
In the Plan Amount text-box I need to display the cost of which category is selected from the above selection. Now I need to enter the amount. IF is selected planId = 1, I need to display 500 in the text-box. Also i need to edit those value and send as as ajax request.
How can I able to get the result as such.
My vue js code is
vBox = new Vue({
el: "#vBox",
data: {
plansb: [],
plan: '',
plan_amt: '',
},
mounted: function() {
var vm = this;
$.ajax({
url: "http://127.0.0.1:8000/alpha/get/plan/",
method: "GET",
dataType: "JSON",
success: function(e) {
if (e.status == 1) {
vm.plansb = e.plans;
}
},
});
},
methods: {
handelSubmit: function(e) {
var vm = this;
data = {};
data['plan'] = this.plan;
data['plan_amt'] = this.plan_amt;
$.ajax({
url: 'http://127.0.0.1:8000/alpha/add/post/',
data: data,
type: "POST",
dataType: 'json',
success: function(e) {
if (e.status)
{
$("#alertModal").modal('show');
$(".alert").removeClass("hidden").html("Your data has been successfully recorded");
vm.pid=e.pid;
console.log(vm.pid);
}
else {
vm.response = e;
alert("Registration Failed")
}
}
});
return false;
},
Can anybody please help me to obtain the result. Based on the selection of plans from the select, I need to update the values in the text box. Please help me to have a result.
You need to add change event of list and get the planid of palns, and according to planid get cost of it and assign it to cost(text-box) model where u want to show change plan cost

Show a square with different background for every option in ng-options

I have this model:
"PRIORITY": [{
"id": 651,
"label": "Haute",
"colorCode": "#ff001e",
"active": true
},
{
"id": 652,
"label": "Moyenne",
"colorCode": "#ffbe33",
"active": true
}];
And I must show for every option a small square before label value with background-color: colorCode.
In view, I have this:
<select
class="full-width"
ng-model="dossier.priorityId"
ng-options="item.id as item.label for item in reference.PRIORITY"
ng-disabled="dossier.statut !== 'EN_COURS_CREATION'"
epf-options-class>
<option value=""></option>
</select>
It's possible to do this in angular 1?
Thanks!
Not possible with options. You have to use custom directive or try this one, It is simple you just have to modify its template and directive.

AngularJS Select preselect not working

Preselection is not working in the select field even though the objects are equal:
<select ng-show="isEditMode(todo.id)" id="assignee" name="assignee"
ng-model="todo.assignee" required
ng-options="user.name for user in users">
</select>
todo.assignee contains a user object, which should match one from users.
It seems that Angular does not recognize that the User object from todo.assignee is contained in users. Can I perform this mapping manually?
The select is shown with no value selected. I can choose a user (from users) and save the record without any problem.
Controller
$scope.todos = Todo.query();
$scope.users = User.query();
Update
As requested in the comments. Structure of the given objects:
$scope.todos
[
{
"id": 157,
"description": "my description 0",
"deadline": 1392073200000,
"assignee": {
"id": 34,
"name": "User 1",
"email": "user1#hotmail.com"
},
"comment": "my comment 0",
"done": true
}
...
]
$scope.users
[
{
"id": 34,
"name": "User 1",
"email": "user1#hotmail.com"
},
{
"id": 35,
"name": "User 2",
"email": "xxc#gmail.com"
},
{
"id": 36,
"name": "User 3",
"email": "xx#hotmail.com"
}
]
The scope of the select comes from a repeat:
<tr ng-repeat="todo in todos | filter:query | filter:{assignee:queryAssignee} | filter:queryDone" ng-class="{danger: isDue(todo)}">
<td>
According to your description:
todo.assignee contains a user object
But your options' value are user.name strings, one object and one string will never be matched.
So, replace
ng-model="todo.assignee"
to
ng-model="todo.assignee.name"
UPDATE:
use ng-options="user.name as user.name for user in users"
Full Answer:
<select ng-show="isEditMode(todo.id)"
ng-model="todo.assignee.name" required
ng-options="user.name as user.name for user in users">
</select>
Plnkr:
http://plnkr.co/edit/A1XdMYmACNCr3OwBuFhk?p=preview
select as label for value in array
label: The result of this expression will be the label for element. The expression will most likely refer to the value variable (e.g. value.propertyName).
you can have refer here:
http://docs.angularjs.org/api/ng.directive:select
UPDATE2:
To fix the side effect, you can use option with separated value and display name
<select ng-model="todo.assignee" required>
<option ng-repeat="user in users" value="{{user}}" ng-selected="todo.assignee.name === user.name">
{{user.name}}
</option>
</select>
Plnkr:
http://plnkr.co/edit/6tzP9ZexnYUUfwAgti9b?p=preview
Explanation:
Before:
When you select one of option, it assign option value to model todo.assignee.name, so only change the name.
todo.assignee.name = "User 3" // like this
todo.assignee // didn't change the id & email
/* {"id": 34,
"name": "User 1",
"email": "user1#hotmail.com"} */
But, Now:
When you select one of option, it assign object value to model todo.assignee, so let what you want.
todo.assignee.name = {
"id": 36,
"name": "User 3",
"email": "user3#hotmail.com"
} // like this
todo.assignee // now change the whole value
/* {"id": 36,
"name": "User 3",
"email": "user3#hotmail.com"} */
Maybe it can be useful for someone else:
<select ng-show="isEditMode(todo.id)" id="assignee" name="assignee"
ng-model="todo.assignee" required
ng-options="user as user.name for user in users track by user.id">
</select>
The magic trick is in "track by user.id"
https://docs.angularjs.org/api/ng/directive/ngOptions

Categories