updating a json value with angular - javascript

I am trying to update an json object value from a textbox using angular and I'm not sure what the best way to go about it is.
This is the json object...
$scope.productAttributes = {
"CostRequirements":[
{
"OriginPostcode": 'NW1BT',
"BearerSize":100
}
]
}
And when a use types in a text field and clicks a button, I would like to grab that textfield value and pass it into the json object to replace the postcose value (OriginPostcode) I tried to pass in a scope variable but that didnt work.
<input type="text" placeholder="Please enter postcode" class="form-control" ng-model="sitePostcode"/>
And this is the fucntion that is fired when the user clicks a button to submit the json
var loadPrices = function () {
productsServices.getPrices1($scope.productAttributes)
.then(function (res) {
$scope.selectedProductPrices = res.data.Products;
// $scope.selectedProductAddOns = res.data.product_addons;
})
.finally(function () {
$scope.loadingPrices = false;
$scope.loadedPrices = true;
});
};
Could anyone tell me what I need to do to put the user input in the textbox into the json object?
Many thanks

What we don't see is the function that runs the update with the button. It should look something like this
// your HTML button
<button ng-click='updateThingy()'>Update</button>
// your HTML input
<input type="text" ng-model="myObject.sitePostcode"/>
// your controller
$scope.myObject = { // ties to the ng-model, you want to tie to a property of an object rather than just a scope property
sitePostcode : $scope.productAttributes.CostRequirements[0].OriginPostcode // load in post code from productAttributes
};
$scope.updateThingy = function(){
$scope.productAttributes.CostRequirements[0].OriginPostcode = $scope.myObject.sitePostcode;
};
Here is a demo plunker for updating a value on button click, hope it helps out.
http://plnkr.co/edit/8PsVgWbr2hMvgx8xEMR1?p=preview

I guess loadPrices function is inside your controller. Well, then you should have sitePostCode variable available inside your controller and your function. So you just need to inject that value inside $scope.productAttributes.
$scope.productAttributes.sitePostCode = $scope.sitePostCode;
This you need to put it before you make the productsServices.getPrices1 call.
var loadPrices = function() {
$scope.productAttributes.sitePostCode = $scope.sitePostCode;
productsServices.getPrices1($scope.productAttributes)
.then(function(res) {
$scope.selectedProductPrices = res.data.Products;
// $scope.selectedProductAddOns = res.data.product_addons;
})
.finally(function() {
$scope.loadingPrices = false;
$scope.loadedPrices = true;
});
};
Let me know if it worked.

Related

Why isn't my localStorage.setItem() and localStorage.getItem() storing a value?

I want to store a user input value using localStorage then use that value in my countdown timer.
Here is the HTML where the user inputs their data:
<form action='/' method= 'GET' id='settings'>
<label> Work Time </label>
<input class='settingInput' type='number' id='workInput'>
<label id='short-break'> Short Break </label>
<input class='settingInput' id='shortBreak'>
<label id='long-break'> Long Break </label>
<input class='settingInput' id='longBreak'>
<button id = 'set-values'>Submit</button>
</form>
this is the javascript to store and retrieve the data:
var workInputValue = document.getElementById('workInput').value;
var workTimeSerialized = JSON.stringify(document.getElementById('workInput').value);
var workTimeFinal = JSON.parse(localStorage.getItem('workTimeKey'));
submitButton.addEventListener('click', (e) => {
localStorage.setItem('workTimeKey', workTimeSerialized);
console.log('submit pressed');
e.preventDefault();
})
Here is the codepen for the whole project: https://codepen.io/Games247/pen/XWJqebG
This is my first time using setItem and getItem so I may be overlooking something obvious.
Currently it looks like a pair of brackets is stored in the localStorage where workTimeKey should be.
Your linked code on codepen has a problem, in fact the code posted here corrects said problem.
var workTimeSerialized = JSON.stringify(document.getElementById('workInput'));
The above is your codepen, the problem is you are trying to serialize the HTML element to JSON rather than it's value hence the '{}' you see in your session storage.
You need to ensure it's the value of the input element and not the element itself you serialize. Like i mentioned, your code posted here resolves the issue ;
var workTimeSerialized = JSON.stringify(document.getElementById('workInput').value);
Note: Whenever you see '[]' or '{}' in session storage rather than your intended value, you are either passing an object directly or an element in your case.
Edit:
'you are most likely not either'
Your input values should be read in the submit click handler otherwise, you get the value of the input before sumbit and not after
So your code:
var workInputValue = document.getElementById('workInput').value;
var workTimeSerialized = JSON.stringify(document.getElementById('workInput').value);
var workTimeFinal = JSON.parse(localStorage.getItem('workTimeKey'));
submitButton.addEventListener('click', (e) => {
localStorage.setItem('workTimeKey', workTimeSerialized);
console.log('submit pressed');
e.preventDefault();
})
becomes:
submitButton.addEventListener('click', (e) => {
var workInputValue = document.getElementById('workInput').value;
var workTimeSerialized = JSON.stringify(document.getElementById('workInput').value);
var workTimeFinal = JSON.parse(localStorage.getItem('workTimeKey'));
localStorage.setItem('workTimeKey', workTimeSerialized);
console.log('submit pressed');
e.preventDefault();
})

angularjs change in model renders only on clicking somewhere

I am working on a search suggestion functionality using firebase and angular js. Basically on key up of a search input box, I call the below function:
scope.suggestString = {};
scope.search = function(){
scope.suggestString = {};
firebaseDb.ref("users")
.orderByChild("Name")
.startAt(scope.searchedString)
.endAt(scope.searchedString + "\uf8ff")
.on("value", function(snapshot) {
snapshot.forEach(function(childSnapshot) {
if(scope.suggestString.hasOwnProperty(childSnapshot.key) == false){
scope.suggestString[childSnapshot.key] = childSnapshot;
}
});
});
}
HTML:
<form>
<input type="text" ng-model="searchedString" ng-keyup="search()">
<ul>
<li ng-repeat="(key,item) in suggestString">
{{item.val().firstName}}
</li>
</ul>
</form>
The code works , the call goes to firebase and fetches the records but I have to click somewhere in search input box for the suggestions to be displayed.
I tried using scope.$apply() but its not working .Its says already applying scope
maybe you can use something like:
<input ng-model="searchedString" ng-model-options="{debounce: 1000}" type="text">
on input box, which will update ng-model (searchString) with search string in input element, after 1 second delay of typing.
After that you can put something like:
scope.$watch('searchedString', (newVal,oldVal)=>{
scope.suggestString = {};
if(scope.searchedString.length <3){
return;
}
firebaseDb.ref("users")
.orderByChild("Name")
.startAt(scope.searchedString)
.endAt(scope.searchedString + "\uf8ff")
.on("value", function(snapshot) {
snapshot.forEach(function(childSnapshot) {
if(scope.suggestString.hasOwnProperty(childSnapshot.key) == false){
scope.suggestString[childSnapshot.key] = childSnapshot;
}
});
});
});
Now it should work if your code for getting data is correct.
Angular doesn't know about this async call, so you have to trigger a digest. You can do that safely without getting a console error by calling $evalAsync after you get the response:
// ...
.on("value", function (snapshot) {
scope.$evalAsync(function () {
snapshot.forEach(function (childSnapshot) {
if (scope.suggestString.hasOwnProperty(childSnapshot.key) == false) {
scope.suggestString[childSnapshot.key] = childSnapshot;
}
})
});
});
But I suspect scope.$apply will be fine too, if you do it outside the loop as I am doing above.
Another option is to wrap all of this firebase functionality into a separate function (possibly in a service), and return a promise from that function using the $q service, and resolve the firebase response. Then you won't have to manually trigger a digest, since Angular knows about the $q service.
Safe apply was the thing I was looking for, the search is smooth now.

Angularjs select "fake" model updating

I have a form with dropdown:
<select class="form-control input-sm"
ng-disabled="!editMode"
ng-model="case.LawyerParticipation.LawyerID"
ng-options="lawyer.ID as lawyer.Name for lawyer in lawyers"
ng-change="changed()"></select>
Default LawyerID value is "null".
When fired change event then "changed" function show me the value of "case.LawyerParticipation.LawyerID":
$scope.changed = function () {
alert($scope.case.LawyerParticipation.LawyerID);
};
And It show that model changed as I expected. $scope.case.LawyerParticipation.LawyerID changes to value that I select in dropdown.
Next step I want to send this value on the server. I click submit button and function "updateCase" fired:
$scope.updateCase = function () {
alert($scope.case.LawyerParticipation.LawyerID);
$http.post("/case/update", $scope.case ).success(function (updatedCase) {
$scope.case = updatedCase;
});
};
Alert in this function show me that all right and "LawyerID" has new value.
Then "post" happens and in console I see that the model posted on server has LawyerID = "null", it comes also null on server! What I doing wrong? Why it's null?
There might be some typo in your server code, add your server code to the question.
$scope.updateCase = function () {
alert($scope.case.LawyerParticipation.LawyerID);
$http.post("/case/update", {data:$scope.case} ).success(function (updatedCase) {
$scope.case = updatedCase;
});
};

angular controller only picks up the input values changed

I've got a fairly simple angular controller method :
$scope.addComment = function () {
if ($scope.newComment.message) {
$scope.can_add_comments = false;
new Comments({ comment: $scope.newComment }).$save(function (comment) {
$scope.comments.unshift(comment);
return $scope.can_add_comments = true;
});
return $scope.newComment = {};
}
};
And in my form I have a textarea that holds the value of comment :
<textarea class="required" cols="40" id="new_comment_message" maxlength="2500" ng-disabled="!can_add_comments" ng-model="newComment.message" required="required" rows="20"></textarea>
Works great so far, however I do want to send some data, hidden data with the comment as well. So I added something to hold that value :
<input id="hash_id" name="hash_id" ng-init="__1515604539_122642" ng-model="newComment.hash_id" type="hidden" value="__1515604539_122642">
However when I inspect the $scope.newComment it always comes back as an object with only message as it's property, which is the value from the text area, and I don't get the property on the object hash_id.
When I make this input non hidden and I manually type in the value into the input field and submit a form, I do get a object with hash_id property. What am I doing wrong here, not setting it right?
As far as I know, ng-model doesn't use the value property as a "default" (i.e. it won't copy it back into your model). If you want a default, it should be placed wherever the model is defined:
$scope.newComment = { hash_id: "__1515604539_122642", /* Other params */ };
Alternatively, changing the ng-init to an assignment should work (though I would recommend the above solution instead):
<input id="hash_id" name="hash_id" ng-init="newComment.hash_id = '__1515604539_122642'" ng-model="newComment.hash_id" type="hidden">

ngInit not working asynchronously(with $q promise)

Edit:
Plunker is working, actual code isn't:
http://plnkr.co/edit/5oVWGCVeuTwTARhZDVMl?p=preview
The service is contains typical getter\setter stuff, beside that, it functions fine, so I didn't post it's code to avoid TLDR.
TLDR version: trying to ng-init a value fetched with AJAX into the ngModel of the text-area, the request resolves with the correct value, but the textarea remain empty.
parent controller function(talks to the service):
$scope.model.getRandomStatus = function(){
var deffered = $q.defer();
var cid = authService.getCompanyId();
var suggestions = companyService.getStatusSuggestions(cid);
if(suggestions && suggestions.length > 0){
deffered.resolve(suggestions[Math.floor(Math.random(suggestions.length) + 1)].message);
return deffered.promise;//we already have a status text, great!
}
//no status, we'll have to load the status choices from the API
companyService.loadStatusSuggestions(cid).then(function(data){
companyService.setStatusSuggestions(cid, data.data);
var result = data.data[Math.floor(Math.random(data.data.length) + 1)];
deffered.resolve(result.message);
},
function(data){
_root.inProgress = false;
deffered.resolve('');
//failed to fetch suggestions, will try again the next time the compnay data is reuqired
});
return deffered.promise;
}
child controller:
.controller('shareCtrl', function($scope){
$scope.layout.toggleStatusSuggestion = function(){
$scope.model.getRandomStatus().then(function(data){
console.log(data);//logs out the correct text
//$scope.model.formData.shareStatus = data;//also tried this, no luck
return data.message;
});
$scope.model.formData.shareStatus = $scope.layout.toggleStatusSuggestion();//Newly edited
}
});
HTML:
<div class="shareContainer" data-ng-controller="shareCtrl">
<textarea class="textAreaExtend" name="shareStatus" data-ng-model="model.formData.shareStatus" data-ng-init="model.formData.shareStatus = layout.toggleStatusSuggestion()" cols="4"></textarea>
</div>
I believe what you are wanting is :
$scope.model.getRandomStatus().then(function(data){
$scope.model.formData.shareStatus = data.message;
});
Returning something from within then does not return anything from the function wrapping it and therefore does nothing
Turns out that I had a custom validation directive that was watching the changes in the model via $formatters, and limting it to 80 chars(twitter), it was failing silently as I didn't expect to progmatically insert invalid values into my forms, very stupid, but could happen to anyone.
Had to make some changes to it, so it's worth to remember in case it happens to anyone else.

Categories

Resources