AngularJS - Ng-model becomes null after changing view - javascript

I have a page called Personal Info page with assigned ng-models.
e.g.
<input type = "text" name = "foo_name" ng-model = "foo.name" />
<input type = "text" name = "foo_address" ng-model = "foo.address" />
<input type = "text" name = "foo_age" ng-model = "foo.age" />
Then, there's a Continue button that redirects to a new page called Other Details.
The Continue button is validating all required fields if filled in. It's also returning a log if all fields are validated - either:
SUCCESS
{result:
{ error: null }
}
FAIL
{result:
{ error:
{
blah blah blah
}
}
}
In the Other Details page, it's just a GRID of the details entered on the previous page. And then, there's an "Edit" button in this page if they wanted to edit something on their personal info.
I'm using ng-model to retrieve the data being stored in the saveDetailsInfo service.
$scope.retrieveData = function(dataFromService) {
$scope.foo = {
name: dataFromService.entry.name,
address: dataFromService.entry.address,
}
}
Then, it's showing nicely and properly on its respective fields. The problem is if I'm trying to hit the "Continue" button again to save my changes. It's returning an error that these fields are already undefined, although the values have been printed and populated on the input fields.
Why has it become null?

I can't recreate the problem...but a quick fix is to check if the value is null on the continue function and if it's null then read the value from the ng-model again(as it's shown in the dom tree) and then using those data to initialize and continue what you need to do with the data.
Many times this happen because the function is initialized before the dom gets it data and hence null...

Related

Set variables for multiple input IDs derived from JSON object

Directly below, the user clicks the link, which calls a PHP script and returns a JSON object, through which I parse and create INPUT fields each with their own ID, which was part of the JSON object:
$(function()
{
$('.addNewLink').click(function(e)
{
e.preventDefault();
$('#addNewForm input, #addNewForm select').val('');
$.post('api/size_types.php', function(data)
{
var obj = JSON.parse(data);
$('.size_types').empty();
var htmlToInsert = obj.map(function (item)
{
return '<div class="input-group">
<span class="input-group-addon" >'+item.SIZE_TYPE+'</span>
<input type="text" class="form-control size_types"
id="'+item.SIZE_TYPE+'" value="'+item.DEFAULT_TEU+'" />
</div>';
});
$('.size_types').html(htmlToInsert);
});
$('#addNewModal').modal('show');
});
});
In the code above, I was able to loop through the JSON and create INPUT fields all with their own ID's using item.SIZE_TYPE and have the values set to item.DEFAULT_TEU.
On the HTML side, there is a form, but hopefully I don't have to show that code. Just know there is a submit button with an ID called #addNewSubmit, which I will display the JavaScript directly below:
$('#addNewSubmit').click(function()
{
var addservice = $('#addservice').val(); // user entered field
// here is where I'm stuck
});
What I need to do is create variables using the INPUT fields automatically created by the JSON object. In my current case, 58 INPUT fields have been generated, all with their own ID and DEFAULT_VALUE. The user has the option to change the DEFAULT_VALUE.
After searching the web, I found this code and added it to the click event directly above, right beneath the first variable:
var size_types=new Array();
var j=0;
$(".size_types").each(function(){ // looking at the class, I need the ID
size_types[j]=$(this).val();
j++;
});
Using this, I can return the values of each of the INPUT fields in an ALERT box, but I need the IDs so I can send them all to a PHP script to INSERT into a database.
How can I get each ID and its VALUE and set them all to their own variables? Or, is there another way to do this?

how to send input text value in another view?

I am trying to send data from one view to another view using routing .I need to send input field value from one screen to another screen using routing .In other words I have one input field and button .On button click I need to send input field value on another screen using routing
here is my code
http://plnkr.co/edit/pl0C88Ksf5Y8YiSnLxSZ?p=preview
On button click I do like this
moveTonext: function(){
// new SecondView({ model: new Backbone.Model({ value: this.$("input").val()}) });
new Router().navigate('secondView/'+this.$("input").val(), { trigger: true });
},
on routing I do like this
secondView: function(inputtext) {
alert(inputtext+"---");
new SecondView();
}
But after that I am getting error this
Cannot read property 'toJSON' of undefined
You need to pass a model to the constructor of your SecondView object. Otherwise, the call to this.$el.html(this.template(this.model.toJSON())); fails (in SecondView.render).
In router.js:
secondView: function(inputtext) {
// create or find somemodel and then:
new SecondView({model: somemodel});
}

Angular select multiple not refreshing on model change

I have the following issue with angular and the html select-input:
When the user loads the page my select is empty until the data is loaded and returned from the corresponding service.
In this case the select is populated correctly.
However, the user should be able to filter the model with a click on a button.
When I press the button a new request is send to the REST-API and the response contains the new model for the select.
Unfortunately, the select won't update correctly even when I change it's model
Here is some code to illustrate my problem:
// This happens in my controller
EventService.getAvailableRooms(requestObject).then(function successCallback(response){
// sanatizeRoomTypes is used to generate user-friendly names instead of [1, 2,..]
vm.rooms = DataSanatizer.sanatizeRoomTypes(response.data);
}, function errorCallback(response){
console.log(response)
});
vm.rooms is the model of my select:
<select id="roomSelect" ng-model="eventCtrl.selectedRooms"
ng-options="room.name group by room.type for room in eventCtrl.rooms track by room.id" multiple required>
</select>
In some cases the select duplicates it's model or looses entries. It seems like there is some sort of data binding problem.
Thanks,
Try wrapping your model changes in $scope.apply :
$scope.$apply(function() {
$scope.data.myVar = "Another value";
});
Read here for more info:
http://tutorials.jenkov.com/angularjs/watch-digest-apply.html
You can also use $scope.$watch on the changing $scope variables to update them in your view.

Assign Value to ViewData in Razor

I would like to store some user inputs into a cookie on the client side. Using MVC3/Razor. Data entered into several DropDownLists. Examople of one below:
<div style="float: left;">
#Html.Telerik().DropDownList()
.Name("name").BindTo((SelectList)#ViewBag.Filter1SelectList)
.Placeholder("All")
.ClientEvents(events => events
.OnChange("onChangeFilter1"))
</div>
I created the following JavaScript in an attempt to store values as the dropdown values change.
function onChangeFilter1(e) {
var filter1 = document.getElementById('name').value;
'<%= ViewData["Filter1Value"]%>' = filter1.toString();
}
The idea is to gather several filters from multiple dropdownlists. Data is filtered on submit button. Is this even possible? I saw only one example and copied it carefully but the above errors: Microsoft JScript runtime error: Cannot assign to '[string]'.
Try to put # sign before ViewData, it will allow you to assign your filter value to the ViewData
#ViewData["Filter1Value"] = filter1.toString();

Not able to read value entered in the form

I am new to Javascript. I am hacking one application wherein I
need to get the values from the form and do processing on it :
icode=document.forms[0].intcode;
lamt=document.forms[0].lnamt.value;
nom =document.forms[0].nomon.value;
and update the values in the other fields in the form depending on the
above three values like this :
document.forms[0].monpmt.value=Math.round(mamt);
document.forms[0].totamt.value=totamt;
Note: these values must automatically appear in the form depending on the above three
values entered by the user.
function setTotamt() {
icode=document.forms[0].intcode;
lamt=document.forms[0].lnamt.value;
nom =document.forms[0].nomon.value;
intrate=icode.options[icode.selectedIndex].myvalue;
if(lamt >0 && nom>0 && intrate>0) {
document.forms[0].monpmt.value=Math.round(mamt);
document.forms[0].totamt.value=totamt;
}
}
I am doing this on Linux platform and tomcat.
> icode=document.forms[0].intcode;
> lamt=document.forms[0].lnamt.value;
> nom =document.forms[0].nomon.value;
Variables should be declared with var to keep them local (presuming the above is intended to be in a function). The syntax is more or less correct, it suggests an HTML structure like:
<form ...>
<input name="intcode" ... >
<input name="lnamt" ... >
<input name="nomon" ... >
...
<input name="monpmt" ...>
<input name="totamt" ...>
</form>
So if you have a button in the form that runs a function to get some values and update the value of some other control, it might look like:
<input type="button" onclick="updateForm(this);" ...>
and the update function might look like:
function updateForm(el) {
var form = el.form; // store a reference to the form
var icode = document.forms[0].intcode; // reference to element named "intcode"
// Get the value of some controls
var lamt = document.forms[0].lnamt.value;
var nom = document.forms[0].nomon.value;
// Do something with the values
var mamt = ...;
...
var totamt = ...;
// Set some values in the form
// Have a reference to the form so use it
form.monpmt.value = Math.round(mamt);
form.totamt.value = totamt;
}
Note that form control values are always strings and that you should test the values you get to make sure they are what you expect. If you want to update values without the user pressing a button[1] you can use the blur event to call updateForm.
You will need validation of input values and to deal with errors (updates before the user has filled in all the fields and invalid data being the obvious ones). Also you'll likely want to format the data when putting it back, such as formatting numbers to two decimal places perhaps.
A button is best as it can be a submit button so that if javascript is disabled or not working, the form is submitted and updated at the server and an updated form returned. If scripting is available, you can cancel the submit and do the processing on the client. You could have the update on the blur event and button if you want.

Categories

Resources