AngularJS Selection - setting ng-model in controller does not update selected value - javascript

I'm facing a problem in upgrading my ng-model in selection.
I have the following HTML:
<div ng-app>
<div ng-controller="Ctrl">
<select ng-model="viewmodel.inputDevice"
ng-options="i.label for i in viewmodel.inputDevices">
</select>
</div>
</div>
And the following code:
function Ctrl($scope) {
// view model
$scope.viewmodel = new function () {
var self = this;
var elem1 = {
value: '1',
label: 'input1'
};
var elem2 = {
value: '2',
label: 'input2'
}
self.inputDevices = [elem1, elem2];
self.inputDevice = {
value: '1',
label: 'input1'
};
};
}
You can use the following JSFiddle
What I want to do is put in inputDevice the same values that the first device has in the collection inputDevices.
I know that I can pass elem1 and it will work however i can't do it since i want to save the selection in Local Storage and than restore it to the ng-model object.
Any suggestion will be grateful
Thanks

You can either store the value instead of the object as Maxim has demonstrated, or you can pull the correct value from the inputDevices array with something like:
self.inputDevice = self.inputDevices.filter(function(item) {
return item.value == storedValue.value;
})[0];
as per an updated fiddle

The code in the original question works for me:
<div ng-app>
<div ng-controller="Ctrl">
<select ng-model="viewmodel.inputDevice"
ng-options="i.label for i in viewmodel.inputDevices">
</select>
<!-- displays the initial and any further selections
correctly as : {"value":"1","label":"input1"} -->
<span>{{viewmodel.inputDevice}}</span>
</div>
</div>
Your js code code works no doubt, but the viewmodel can be build a little easier:
function Ctrl($scope) {
// view model
$scope.viewmodel = {inputDevices: [
{value: '1', label: 'input1'},
{value: '2', label: 'input2'}
]};
$scope.viewmodel.inputDevice = $scope.viewmodel.inputDevices[0];
}
jsfiddle http://jsfiddle.net/8t2Ln/39/

Instead:
self.inputDevice = {
value: '1',
label: 'input1'
};
I would store index only:
self.inputDevice = 0; // or 1 - second item
and:
<select>
<option ng-repeat="i in viewmodel.inputDevices"
value="{{i.label}}"
ng-selected="viewmodel.inputDevices.indexOf(i) == viewmodel.inputDevice"
>{{i.label}}</option>
</select>
This way will work.
Fixed Demo Fiddle

Related

Unable to get optionsValue to work with dependent dropdowns and the Knockout mapping plugin

I am a database developer (there's the problem) tasked with emitting JSON to be used with Knockout.js to render sets of dependent list items. I have just started working with Knockout, so this is likely something obvious that I am missing.
Here is the markup:
<select data-bind="options:data,
optionsText:'leadTime',
value:leadTimes">
</select>
<!--ko with: leadTimes -->
<select data-bind="options:colors,
optionsText:'name',
optionsValue:'key',
value:$root.colorsByLeadTime">
</select>
<!--/ko-->
Here is the test data and code:
var data = [
{
key:"1",
leadTime:"Standard",
colors:[
{ key:"11", name:"Red" },
{ key:"12", name:"Orange" },
{ key:"13", name:"Yellow" }
]
},
{
key:"2",
leadTime:"Quick",
colors:[
{ key:"21", name:"Black" },
{ key:"22", name:"White" }
]
}
]
var dataViewModel = ko.mapping.fromJS(data);
var mainViewModel = {
data:dataViewModel,
leadTimes:ko.observable(),
colorsByLeadTime:ko.observable()
}
ko.applyBindings(mainViewModel);
As this stands, it correctly populates the value attribute of the second select list. However, if I add optionsValue:'key' to the first select list then the value attribute for that is set correctly but the second select list renders as an empty list.
All I need is for the value attribute of the option tag to be set to the key value provided in the data, regardless of where the select list is in the set of dependent lists. I've looked at many articles and the docs, but this particular scenario (which I would think is very common) is eluding me.
Here is a jsfiddle with the data, JS, and markup as given above: http://jsfiddle.net/tnagle/Lyxjt11y/
To really see the issue, you can add the following code after the initialization of mainViewModel.
mainViewModel.leadTimes.subscribe(function(newValue) {
console.log(newValue);
debugger;
});
Before adding the optionsValue:'key', line above will log the following output.
Object {key: function, leadTime: function, colors: function}
But after adding optionsValue:'key', it log the following output.
"1"
or
"2"
The reason it failed was because when you assign optionsValue: 'key' to the first select list, leadTimes property of your mainViewModel which before will contain an object that has property color, now will be set to a string object. Then the select list just failed to find color property from leadTimes that has changed to a string object.
One of the way to make it work is by changing to this:
var data = [
{
key:"1",
leadTime:"Standard",
colors:[
{ key:"11", name:"Red" },
{ key:"12", name:"Orange" },
{ key:"13", name:"Yellow" }
]
},
{
key:"2",
leadTime:"Quick",
colors:[
{ key:"21", name:"Black" },
{ key:"22", name:"White" }
]
}
]
var dataViewModel = ko.mapping.fromJS(data);
var mainViewModel = new function (){
var self = this;
self.data = dataViewModel;
self.leadTimes = ko.observable();
self.selectedKey = ko.observable();
self.selectedKey.subscribe(function(selectedKey){
self.selectedData(ko.utils.arrayFirst(self.data(), function(item) {
return item.key() == selectedKey;
}));
}, self);
self.colorsByLeadTime = ko.observable();
self.selectedData = ko.observable();
}
ko.applyBindings(mainViewModel);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.3.5/knockout.mapping.js"></script>
<select data-bind="options:data,
optionsText:'leadTime',
optionsValue:'key',
value:selectedKey">
</select>
<!--ko with: selectedData -->
<select data-bind="options:colors,
optionsText:'name',
optionsValue:'key',
value:$root.colorsByLeadTime">
</select>
<!--/ko-->

AngularJS: How to freeze orderBy in ng-repeat during edit mode

I'm using md-data-table and I have add sorting options based on column.
Below, presented my html(pug format) code:
table(md-table md-row-select multiple='' ng-model='vm.selected' md-progress='promise')
//- columns
thead(md-head class='back-color')
tr(md-row)
th(md-column ng-click='vm.orderingBy(name)')
span Name
th(md-column ng-click='vm.sortingBy(code)')
span Code
//- rows
tbody(md-body)
tr(md-select='record' md-select-id='id' ng-repeat='record in vm.records | orderBy:vm.orderByColumn)
//- name
td(md-cell)
p(ng-hide='vm.columns.edit') {{record.name}}
md-input-container(ng-if='vm.columns.edit' class='no-errors-spacer md-no-margin')
input(ng-model='record.name' md-select-on-focus)
//- code
td(md-cell)
p(ng-hide='vm.columns.edit') {{record.sorting_code}}
md-input-container(ng-if='vm.columns.edit' class='no-errors-spacer md-no-margin')
input(ng-model='record.code' md-select-on-focus)
My AngularJS(Javascript) code presented below:
vm.orderByColumn = 'name';
vm.orderingBy = function(ordering) {
vm.orderByColumn = ordering;
}
The problem is when the table is ordered by 'code' and I'm trying to edit the record's code, the order of records changing while you change the value of code. So, the result is very confused.
I'm thinking if there is any way to freeze the order while I'm in edit mode.
Outsource your orderBy logic into your controller and make it block in edit mode by using a simple switch variable like in this example fiddle. I hope this working example will help you to implement this logic inside your application.
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope, orderByFilter) {
$scope.edit = false;
$scope.data = [{
name: 'Frank'
},{
name: 'Peter'
},{
name: 'Basti'
},{
name: 'Sven'
},{
name: 'Franky'
},{
name: 'Sveny'
},{
name: 'bob'
}];
$scope.order = {
column: '',
revers: false
}
$scope.toggleEditMode = function () {
$scope.edit = !$scope.edit;
}
$scope.orderBy = function (column) {
if (!$scope.edit) {
$scope.order.column = column;
$scope.order.reverse = !$scope.order.reverse; //toggle revers
$scope.data = orderByFilter($scope.data, $scope.order.column, $scope.order.reverse);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<div>
<h3 ng-click="orderBy('name')">
Name
</h3>
<p ng-repeat="item in data">
<input type="text" ng-model="item.name" ng-if="edit" />
<span ng-if="!edit">{{ item.name }}</span>
</p>
</div>
<button ng-click="toggleEditMode()">
Toggle edit mode
</button>
</div>
</div>
I had this issue for a while and I've found a pretty simple solution. I made the sorting method by myself using $filter,
On my case : Instead of
<tr ng-repeat="schedule in schedules | orderBy:filerTable2:filterasc track by $index">
I just put
<tr ng-repeat="schedule in schedules">
And I used setFiler method to sort the list using filter parameter as the filter name.
$scope.setFiler = function(filter){
if($scope.filerTable2 == filter){
$scope.filterasc = !$scope.filterasc;
}
else{
$scope.filerTable2 = filter;
$scope.filterasc = false;
}
$scope.schedules = $filter('orderBy')($scope.schedules, filter, $scope.filterasc);
};

prevent reflecting ng-model value across all select tags

I am pretty new to AngularJS. I am working on a project wherein I need to append certain html select tags based on a button click. Each select tag is bound to a ng-model attribute (which is hardcoded). Now the problem I am facing is, once I append more than 2 such html templates and make changes in a select tag then value selected is reflected across all the tags bound to the corresponding ng-model attribute (which is pretty obvious). I would like to know if there is a way around it without naming each ng-model differently.
JS code:
EsConnector.directive("placeholderid", function($compile, $rootScope, queryService, chartOptions){
return {
restrict : 'A',
scope : true,
link : function($scope, element, attrs){
$scope.current_mount1 = "iscsi";
$scope.current_dedupe1 = "on";
$scope.y_axis_param1 = "Total iops";
var totalIops =[];
var totalBandwidth =[];
element.bind("click", function(){
$scope.count++;
$scope.placeholdervalue = "placeholder12"+$scope.count;
var compiledHTML = $compile('<span class="static" id='+$scope.placeholdervalue+'>choose mount type<select ng-bind="current_mount1" ng-options="o as o for o in mount_type"></select>choose dedupe<select ng-model="current_dedupe1" ng-options="o as o for o in dedupe"></select>choose y axis param<select ng-model="y_axis_param1" ng-options="o as o for o in y_axis_param_options"></select></span><div id='+$scope.count+' style=width:1400px;height:300px></div>')($scope);
$("#space-for-buttons").append(compiledHTML);
$scope.$apply();
$(".static").children().each(function() {
$(this).on("change", function(){
var id = $(this).closest("span").attr("id");
var chartId = id.slice(-1);
queryService.testing($scope.current_mount1, $scope.current_dedupe1, function(response){
var watever = response.hits.hits;
dataToBePlot = chartOptions.calcParams(watever, totalIops, totalBandwidth, $scope.y_axis_param1);
chartOptions.creatingGraph(dataToBePlot, $scope.y_axis_param1, chartId);
});
});
});
});
}
}
});
Code explanation:
This is just the directive which I am posting.I am appending my compiledHTML and doing $scope.apply to set the select tags to their default values. Whenever any of the select tags are changed I am doing a set of operations (function calls to services) on the values selected.
As you can see the ng-model attribute being attached is the same. So when one select tag is changed the value is reflected on all the appended HTML even though the data displayed does not match to it.
Hope this PLunker is useful for you. You need to have one way binding over such attributes
<p>Hello {{name}}!</p>
<input ng-model="name"/>
<br>Single way binding: {{::name}}
Let me know if I misunderstood your question
It is a bit hard to understand your whole requirement from your description and your code, correct me if I'm wrong: you are trying to dynamically add a dropdown on a button click and then trying to keep track on each of them.
If you are giving the same ng-model for each generated items, then they are bound to the same object, and their behavior is synchronized, that is how angular works.
What you can do is, change your structure to an array, and then assigning ng-model to the elements, so you can conveniently keep track on each of them. I understand you came from jquery base on your code, so let me show you the angular way of doing things.
angular.module('test', []).controller('Test', Test);
function Test($scope) {
$scope.itemArray = [
{ id: 1, selected: "op1" },
{ id: 2, selected: "op2" }
];
$scope.optionList = [
{ name: "Option 1", value: "op1" },
{ name: "Option 2", value: "op2" },
{ name: "Option 3", value: "op3" }
]
$scope.addItem = function() {
var newItem = { id: $scope.itemArray.length + 1, selected: "" };
$scope.itemArray.push(newItem);
}
$scope.changeItem = function(item) {
alert("changed item " + item.id + " to " + item.selected);
}
}
select {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
<div ng-app='test' ng-controller='Test'>
<button type='button' ng-click='addItem()'>Add</button>
<select ng-repeat='item in itemArray'
ng-options='option.value as option.name for option in optionList'
ng-model='item.selected'
ng-change='changeItem(item)'></select>
</div>

Error while binding the selected value with DevExtreme and KnockOut

I trying to develop a little app.
I have made a login view and it works, I am able to bind the data written by the user. After this, I show two select box. The first is binded with a list (correctly) and the second has to be bind with a list populated after a value is selected from the first.
I'm not able to read the value selected from the first list.
I have this html:
<div class="dx-fieldset">
<div class="dx-field">
<div class="dx-field-label">Rete</div>
<div class="dx-field-value"
data-bind="dxLookup: { dataSource: is_retistiSource, value: rete, displayExpr: 'NOME', title: 'Retisti associati', placeholder: 'Selezionare rete',
onSelectionChanged:setRete }" />
</div>
<div class="dx-field">
<div class="dx-field-label">Impianto</div>
<div class="dx-field-value"
data-bind="dxLookup: { dataSource: is_impiantiSource, value: impianto, displayExpr: 'NOME', title: 'Impianti associati', placeholder: 'Selezionare impianto' }" />
</div>
</div>
and this javascript:
OverviewAPP.afterLogin = function (params) {
var isReady = $.Deferred();
var viewModel = {
rete: ko.observable(""),
impianto: ko.observable(""),
is_retistiSource: OverviewAPP.listaReti,
is_impiantiSource: OverviewAPP.listaImpianti,
setRete: function () {
console.log(viewModel.rete);
var nRetisti = OverviewAPP.listaRetiImpianti.length;
for (i = 0; i < nRetisti; i++) {
if (OverviewAPP.listaRetiImpianti[i]["retista"]["NOME"] == this.rete)
{
OverviewAPP.listaImpianti = listaRetiImpianti[i]["listaImpianti"];
break;
}
}
is_impiantiSource = OverviewAPP.listaImpianti;
},
close: function () {
OverviewAPP.app.back();
}
};
return viewModel;
};
In the setRete function, with the line "console.log(viewModel.rete);", I see this output:
d(){if(0<arguments.length)return d.Wa(c,arguments[0])&&(d.X(),c=arguments[0],d.W()),this;a.k.Ob(d);return c}
Why? How can I bind and read the selected value?
UPDATE: I've done in this way, it works:
setRete: function (e) {
OverviewAPP.IDrete = e.value;
var nRetisti = OverviewAPP.listaRetiImpianti.length;
for (i = 0; i < nRetisti; i++) {
if (OverviewAPP.listaRetiImpianti[i]["retista"]["NOME"] == e.value["NOME"])
{
OverviewAPP.listaImpianti = OverviewAPP.listaRetiImpianti[i]["listaImpianti"];
break;
}
}
//ko.applyBindings(viewModel);
},
But I don't know how update my second list, "is_impiantiSource".
Observables are functions. That's why you get a function in the console. Call the rete function to get its value:
viewmodel.rete();
Also see the Knockout: Observables help topic that describes this (under "Reading and writing observables").
This is how you can obtain a new value. Then, you need to update the dependent lookup data source. For this, make the is_impiantiSource property an observable array:
is_impiantiSource: ko.observableArray(OverviewAPP.listaImpianti),
After this, modify it in setRene like:
viewModel.is_impiantiSource(OverviewAPP.listaImpianti)
Also see Observable Arrays for how to work with arrays in Knockout

How can I get tagetData from pickList in PrimeUI?

I am trying to retrieve the target data from PrimeUI pickList, but with no success. Maybe someone with good knowledges in jQuery can help me. Well, I think my problem is simple. I successfully implemented the pickList from PrimeUI, but I don't know and I can't retrieve the target data from the pickList.
Well, let me show some code. My javascript looks like this:
<script>
$(document).ready(function() {
var mySourceData = [{label: 'Label 1', value: 1}, {label: 'Label 2', value: 2}];
var myTargetData = new Array();
$('#myPickList').puipicklist({
filter: true,
dragdrop: true,
filterMatchMode: 'contains',
sourceData: mySourceData,
targetData: myTargetData
});
$('#myPickListSaveButton').click(function(){
//How to retrieve #myPickList target data?
});
}
</script>
My HTML:
<div id="atividadesPicklist">
<select name="source"></select>
<select name="target"></select>
</div>
Like I wrote inside the #myPickListSaveButton function, how can I retrieve the value from targetData?
Thanks.
The plugin will move the options to the target select, meaning you can simply get the options from that select
$('#myPickListSaveButton').click(function () {
var targetData = $.map($('select[name=target] option'), function (v) {
return v.value; // maps the values and returns them in an array ["1", "2"]
});
console.log(targetData);
});
Example

Categories

Resources