Binding data with dropdown - javascript

I am making an application where there are two drop down's and one text box.There is JSON data i want to bind.I am able to bind the dropdown i.e on the change on first drop down the value of second drop down is changing.The problem is I am not able to bind data with the text field.Can any body help me?
The code for reference is HTML
<select data-bind="options: financialYear,value: animalTypea, optionsText: 'description',optionsValue: 'value'">
</select>
<select data-bind="options: animalsForType,value: animalType, optionsText: 'description',optionsValue: 'value'"></select>
<input type="text" data-bind="value: subject" />
and the JS code is
response.invocationResult.customerRequestMasterDetailBeans.forEach(function (item1) {
if(item1.key == "") {
self.financialYear.push(item1);
}
});
self.financialYear = ko.observableArray([]);
self.animalTypea = ko.observable();
self.financialYeara = ko.observableArray([]);
self.animalTypea = ko.observable();
self.animalType = ko.observable();
self.subject = ko.observable();
self.animalsForType = ko.computed(function () {
var selectedType = self.animalTypea();
return !selectedType ? [] : response.invocationResult.customerRequestMasterDetailBeans.filter(function (data) {
return data.key == selectedType;
});
});
self.subject = ko.computed(function () {
var selectedType = self.animalType();
return !selectedType ? [] : response.invocationResult.customerRequestMasterDetailBeans.filter(function (data) {
return data.subjectMessage == selectedType;
});
});
and for reference the JSON is
{
"customerRequestMasterDetailBeans": [
{
"requestMessage": "",
"subjectMessage": "",
"description": "DocumentRequest",
"value": "DR",
"formatMessage": "",
"serviceCharge": "",
"key": ""
},
{
"requestMessage": "AservicechargeofRs50.00perstatementrequestwillbeapplied.Doyouwanttoproceed?",
"subjectMessage": "HardcopyofStatementofAccount",
"description": "StatementofAccount",
"value": "SDR",
"formatMessage": "PleasesendmeahardcopyofupdatedStatementofAccountatmyregisteredaddress.",
"serviceCharge": "Rs50.00",
"key": "DR"
},
{
"requestMessage": "AservicechargeofRs50.00perstatementrequestwillbeapplied.Doyouwanttoproceed?",
"subjectMessage": "HardcopyofForeclosureSimulation",
"description": "ForeclosureSimulation",
"value": "FCDR",
"formatMessage": "PleasesendmeahardcopyofupdatedForeclosureSimulationatmyregisteredaddress.",
"serviceCharge": "Rs50.00",
"key": "DR"
}
]
}
Actually I am trying to display Document request in first drop down and Statement of Account and Foreclosure Simulation in second drop down.Now if second drop down is populated with Statement of Account the text box should display Statement of Account and if Foreclosure Simulation then Hard copy of Foreclosure Simulation.

From what I can see, your problem is due to binding the value of an input to a computed value, which should depend on the values of the view-model and shouldn't be editable.
I would suggest you use the text binding instead of the value binding and using a span or div instead of an input as explained at http://knockoutjs.com/documentation/computedObservables.html.
<span data-bind="text: subject"></span>
If you really want to be able to edit the value of subject in an input node, (you might want to be able to change the selection by typing something different here) you could use a writable observable to tell knockout what you want to do when you type a value there (great explanation at http://knockoutjs.com/documentation/computed-writable.html).

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-->

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>

Selecting Select Box Option from Controller

I did a lot of searching and tried eleventy-billion different Google search combinations, but all I can find on this issue is how to set a default option in a select box.
I have a page where an admin can select a user from a list of users, and then Angular JS grabs the user_id of that user (using ng-change), sends it to the DB via POST, and then the goal is to change the value of the other inputs to the values from the DB. I have the values, but running into a hitch when using that value to get my state select box to change to the user's state.
The JS in question:
$scope.getUserInfo = function(user_id) {
this.user_id = user_id;
$http.post("lib/scripts/managing_user.php", {func: 'retrieve_user_info', user_id: this.user_id}).
success(function(data) {
console.log(data);
$scope.is_active = data['0']['active'];
//Interacts with the ng-checked directive. It takes a bool, and data returns 0 or 1 in active.
$scope.username = data['0']['username'];
//Assigns the data value to the ng-model directive with the value username
//Have to treat data as a 2D array because that is how it is returned
$scope.email = data['0']['email'];
$scope.fName = data['0']['first_name'];
$scope.lName = data['0']['last_name'];
$scope.schoolList = data['0']['school_id']; (<-Does not work)
}).
I accomplished the same thing using jQuery before. Here is the code if it helps you see what I want to do.
if ($("#school").children("option:selected"))
$("#school").children("option:selected").attr("selected", "false");
$("#school #" + this['school_id'] + "").attr("selected", "true");
Here is the Select Box that I want changed.
<div class="row-fluid">
<span class="adduser_heading">School:</span>
<select id="school" class="adduser_input" ng-model="user.schoolList" ng-options="name.school_name for (key, name) in schoolList" ng-disabled="is_disabled" name="school" style="width: 246px;"></select>
</div>
I get the list of schools from the DB, and that populates that list. After selecting a user, I want this select box to change to that user's school. The ultimate goal is for the admin to be able to change the selected school and submit it, changing the school in the DB.
Hope I described the problem adequately. Basically: I want to select an option in a select box from the JS using Angular JS.
Edit: As per the advice of oware, I created a function that gets just the school name from the object array and returns it to $scope.user.schoolList. Unfortunately, that did not work.
$scope.user.schoolList = $scope.findInSchoolList(data['0']['school_id']);
$scope.findInSchoolList = function(school_id) {
var school_id = school_id;
var school;
school = $scope.schoolList[school_id];
school = school['school_name'];
return school;
};
And here is the format of what is returned from the DB with regards to school. I don't really want to post "data" since that has the information of an actual person. Basically, the information with regards to school is what is below.
school_id: "106"
school_name: "Central Campus High School"
Your ng-model is set to user.schoolList, while you're assigning the default value to $scope.schoolList.
It should be $scope.user.schoolList instead.
If you want to use the find function, you still need to return the right object, not just the name; and you need to fix your function. So something like this should work:
$scope.findInSchoolList = function(school_id) {
for(var i = 0; i < $scope.schoolList.length; i++) {
if ($scope.schoolList[i].school_id == school_id) {
return $scope.schoolList[i];
}
}
};
Here's a working example:
angular.module('app', [])
.controller('Ctrl', function($scope) {
var findInSchoolList = function(school_id) {
for (var i = 0; i < $scope.schoolList.length; i++) {
if ($scope.schoolList[i].school_id == school_id) {
return $scope.schoolList[i];
}
}
};
$scope.schoolList = [{
school_id: "1",
school_name: "Central Campus High School"
}, {
school_id: "106",
school_name: "Another High School"
}, {
school_id: "231",
school_name: "Yet Another High School"
}, {
school_id: "23",
school_name: "The Correct High School"
}, {
school_id: "2",
school_name: "Last High School"
}]
$scope.user = {
schoolList: findInSchoolList(23)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="row-fluid" ng-app="app" ng-controller="Ctrl">
<span class="adduser_heading">School:</span>
<select id="school" class="adduser_input" ng-model="user.schoolList" ng-options="name.school_name for (key, name) in schoolList" ng-disabled="is_disabled" name="school" style="width: 246px;"></select>
</div>
you have to select the item from the array that populated the list, for example, if you have:
$scope.school_list = [{id:1, name:'harvard'}, {id:2, name:'other'}]
and you want to select with:
$scope.user.schoolList = {id:1, name:'harvard'}
it won't work, you have to make a fucntion that finds the element in the array and then assign it to the $scope.user.schoolList variable (that is bound to the ng-model of your list)
you have to do something like this:
$scope.user.schoolList = findInSchoolList({id:1, name:'harvard'})
and it will select the item from the select list
hope it helps

Update related properties in response to observable change

Update
My original post is pretty long - here's the tl;dr version:
How do you update all properties of a knockout model after a single property has changed? The update function must reference an observableArray in the viewModel.
-- More details --
I'm using KnockoutJS. I have a Zoo and a Tapir model and three observables in the viewmodel - zoos, tapirCatalog and currentTapir. The tapirCatalog is populated from the server and the currentTapir holds the value of whichever tapir is being edited at the time.
Here's what I'm trying to accomplish: A user has added a tapir from a list of tapirs to his/her zoo. When viewing the zoo, the user can edit a tapir and replace it with another. To do this a popup window is shown with a select form populated by tapir names and a span showing the currently selected GoofinessLevel.
So, when the select element changes this changes the TapirId in currentTapir. I want that to trigger something that changes the currentTapir's Name and GoofinessLevel.
I tried subscribing to currentTapir().GoofinessLevel but cannot get it to trigger:
function Zoo(data) {
this.ZooId = ko.observable(data.ZooId);
this.Tapirs = ko.observableArray(data.Tapirs);
}
function Tapir(data) {
this.TapirId = ko.observable(data.TapirId);
this.Name = ko.observable(data.Name);
this.GoofinessLevel = ko.observable(data.Name);
}
function ViewModel() {
var self = this;
// Initializer, because I get an UncaughtType error because TapirId is undefined when attempting to subscribe to it
var tapirInitializer = { TapirId: 0, Name: "Template", GoofinessLevel: 0 }
self.zoos = ko.observableArray([]);
self.tapirCatalog = ko.observableArray([]);
self.currentTapir = ko.observable(new Tapir(tapirInitializer));
self.currentTapir().TapirId.subscribe(function (newValue) {
console.log("TapirId changed to: " + newValue);
}); // This does not show in console when select element is changed
};
Oddly enough, when I subscribe to the Goofiness level inside the Tapir model I get the trigger:
function Tapir(data) {
var self = this;
self.TapirId = ko.observable(data.TapirId);
self.Name = ko.observable(data.Name);
self.GoofinessLevel = ko.observable(data.Name);
self.TapirId.subscribe(function (newId) {
console.log("new TapirId from internal: " + newId);
}); // This shows up in the console when select element is changed
}
I suspect that this is a pretty common scenario for people using KO but I haven't be able to find anything. And I've searched for a while now (it's possible that I may not have the correct vocabulary to search with?). I did find this solution, but he references the viewmodel from the model itself -- which seems like back coding since I would think the Tapir should not have any knowledge of the Zoo: http://jsfiddle.net/rniemeyer/QREf3/
** Update **
Here's the code for my select element (the parent div has data-bind="with: currentTapir":
<select
data-bind="attr: { id: 'tapirName', name: 'TapirId' },
options: $root.tapirCatalog,
optionsText: 'Name',
optionsValue: 'TapirId',
value: TapirId">
</select>
It sounds like what you need to do is bind the select to an observable instead of the Id
<select
data-bind="attr: { id: 'tapirName', name: 'TapirId' },
options: $root.tapirCatalog,
optionsText: 'Name',
optionsValue: 'TapirId',
value: currentTapir">
</select>

How do I keep the original value selected when transitioning to edit mode?

The select lists are not rendering with the correct option selected. I've tried this a number of different ways including a computed selected observable (this.selected = ko.computed(return parseInt(selected(), 10) == this.id; )) and find in array functions.
In production, the dataArea elements would be populated with server side data. Using the divs with "data-" attributes keeps server side and client side scripting separate (I find this helps the designers).
A record would be displayed in non edit mode first with the option to edit by clicking the edit button. In edit mode, the initial values for the record appear in input controls. You would have the option to say, choose another customer and the having the form load new associated projects. Loading a new customer would reset the project list as expected.
So while loading a new customer would work well, its the transition to editing the current values that is causing an issue. The selected project needs to appear in the drop down list. If a new customer is chosen, the list populates with new options and no defaults are required.
http://jsfiddle.net/mathewvance/ZQLRx/
* original sample (please ignore) http://jsfiddle.net/mathewvance/wAGzh/ *
Thanks.
<p>
issue: When the select options are read, the inital value gets reset to the first object in the options. How do I keep the original value selected when transitioning to edit mode?
</p>
<div>
<h2>Edit Quote '1001'</h2>
<div class="editor-row" data-bind="with: selectedCustomer">
<label>Customer</label>
<div data-bind="visible: !$root.isEditMode()">
<span data-bind="text: CompanyName"></span>
</div>
<div data-bind="visible: $root.isEditMode()">
<input type="radio" name="customerGroup" value="1" data-bind="value: id"> Company Name 1
<input type="radio" name="customerGroup" value="2" data-bind="value: id"> Company Name 2
</div>
</div>
<div class="editor-row">
<label>Project</label>
<div data-bind="visible: !isEditMode()">
<span data-bind="text: selectedProject.Name"></span>
</div>
<div data-bind="visible: isEditMode()">
<select data-bind="options: selectedCustomer().projects, optionsText: 'Name', value: selectedProject"></select>
</div>
</div>
<div>
<button data-bind="click: function() { turnOnEditMode() }">Edit</button>
<button data-bind="click: function() { turnOffEditMode() }">Cancel</button>
</div>
</div>
<hr/>
<div data-bind="text: ko.toJSON($root)"></div>
function ajaxCallGetProjectsByCustomer(customerId) {
var database = '[{"CustomerId": 1, "Name":"Company Name 1", "Projects": [ { "ProjectId": "11", "Name": "project 11" }, { "ProjectId": "12", "Name": "project 12" }, { "ProjectId": "13", "Name": "project 13" }] }, {"CustomerId": 2, "Name": "Company Name 2", "Projects": [ { "ProjectId": "21", "Name": "project 21" }, { "ProjectId": "22", "Name": "project 22" }, { "ProjectId": "23", "Name": "project 23" }] }]';
var json = ko.utils.parseJson(database);
//console.log('parseJson(database) - ' + json);
//ko.utils.arrayForEach(json, function(item) {
// console.log('CustomerId: ' + item.CustomerId);
//});
return ko.utils.arrayFirst(json, function(item){
return item.CustomerId == customerId;
});
}
var Customer = function(id, name, projects) {
var self = this;
this.id = ko.observable(id);
this.CompanyName = ko.observable(name);
this.projects = ko.observableArray(ko.utils.arrayMap(projects, function(item) {
return new Project(item.ProjectId, item.Name);
}));
};
Customer.load = function(id) {
var data = ajaxCallGetProjectsByCustomer(id);
var customer = new Customer(
data.CustomerId,
data.Name,
data.Projects);
};
var Project= function(id, name) {
this.id = id;
this.Name = ko.observable(name);
};
var QuoteViewModel = function () {
var self = this;
$customerData = $('#customerData'); // data from html elements
$projectData = $('#projectData');
// intial values to display from html data
var customer = new Customer (
$customerData .attr('data-id'),
$customerData .attr('data-companyName'),
[{"ProjectId": $projectData .attr('data-id'), "Name": $projectData .attr('data-name')}]
)
this.selectedCustomer = ko.observable(customer);
this.selectedProject = ko.observable($projectData.attr('data-id'));
this.isEditMode = ko.observable(false);
this.selectedCustomer.subscribe(function(){
// todo: load customer projects from database api when editing
});
this.turnOnEditMode = function() {
var customerId = self.selectedCustomer().id();
console.log('customerId: ' + customerId);
Customer.load(customerId);
self.isEditMode(true);
};
this.turnOffEditMode = function() {
self.isEditMode(false);
};
};
var viewModel = new QuoteViewModel();
ko.applyBindings(viewModel);
One the initial value you load
this.dongle = ko.observable($dongleData.attr('data-id'));
This would be the string value "3". Where as the dongle html select element is actually saving/expecting to retrieve the object { "Id": "3", "Name": "dongle 3" }.
Here is a working version that gets the correct initial values and allows editing.
http://jsfiddle.net/madcapnmckay/28FVr/5/
If you need to save the a specific value and not the whole dongle/widget object, you can use the optionsValue attribute to store just the id. Here is it working in the same way.
http://jsfiddle.net/madcapnmckay/VnjyT/4/
EDIT
Ok I have a working version for you. I'll try to summarize everything I changed and why.
http://jsfiddle.net/madcapnmckay/jXr8W/
To get the customer info to work
The Customer name was not stored in the ajaxCallGetProjectsByCustomer json so when you loaded a customer there was no way to determine the new name from the data received. I added a Name property to each customer in the json with name "Company Name 1" etc.
To get the projects collection to work
The problem here was as stated originally with the dongles. You initialize the selectedProject observable with $projectData.attr('data-id') which equates to string value of 13. This is incorrect as the select list is configured in such a way that it actually saves/expects to receive the project object itself. Changing this id assignment to an object assignment made the initial value of project work correctly.
var project = ko.utils.arrayFirst(customer.projects(), function(project){
return project.id == Number($projectData.attr('data-id'));
});
this.selectedProject = ko.observable(project);
FYI there was a minor error in the html, the selectedProject.Name needed to be selectedProject().Name. No big deal.
I'm sure you could have figured out those pretty easily. The next bit is where the real issue is. You reload the Customer every time the edit button is clicked. This seems strange and you may want to reconsider that approach.
However what happens is you load a customer object from the server by id. Assign it to the selectedCustomer observable, this actually works fine. But then because the drop down is bound to selectedCustomer().projects and viewModel.selectedProject it expects that selectedProject is a member of selectedCustomer().projects. In the case of objects the equality operator is assessing whether the references match and in your case they do not because the original selectedProject was destroyed with its associated customer when you overwrote the selectedCustomer value. The fact that the ids are the same is irrelevant.
I have put in place a hack to solve this.
var oldProjectId = viewModel.selectedProject().id;
viewModel.selectedCustomer(customer);
var sameProjectDifferentInstance = ko.utils.arrayFirst(customer.projects(), function(project){
return project.id == oldProjectId;
});
viewModel.selectedProject(sameProjectDifferentInstance || customer.projects()[0]);
This saves the old projectId before assigning the new customer, looks up a project object in the new customer object and assigns it or defaults to the first if not found.
I would recommend rethinking when you load objects and how you handle their lifecycle. If you hold the current objects it memory with a full list of projects included you don't need to reload them to edit, simply edit and then send the update back to the server.
You may find it easier to hold json from the server in js variables instead of html dom elements. e.g.
<script>var projectInitialData = '#Model.ProjectInitialData.toJSON()';</script>
Hope this helps.

Categories

Resources