Angular $scope property gets overwritten when passed into function as an argument - javascript

I have an odd situation that I can't seem to figure out.
In Angular 1.4, I have a variable on the scope object used as a model to collect form data, $scope.videoModel. When a form is submitted, the model gets passed into a function, ng-submit="createVideo(videoModel), where a bunch of processing and regex happens. For example, extract a YouTube id.
Everything works as intended, but even though I am passing in the scope object as an argument (payload) to a function , certain attributes that are updated on the argument, also get updated on the $scope.
For eample, if I pass in $scope.videoModel.youtube into createVideo as payload, then extract the Youtube ID and assign it as payload.youtube = payload.youtube.match(regEx);, the $scope.videoModel.youtube property also gets updated. I can see this since the form value gets changed from a complete url to just the id.
It seems that passing in videoModel as an argument to a function does not create a copy to the variable, but instead references it. I can't seem to find anything about it. I believe I could simply create a new variable like this var tempVar = payload, but that seems wacky and I wonder if I'm doing something fundamentally incorrect.
Does videoModel get passed in a reference and not a copy?
Here is a sampling of the code clipped for brevity.
HTML
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">YouTube Url</label>
<div class="col-sm-10">
<input class="form-control" ng-class="{ 'has-error' : newvideo.youtube.$invalid && newvideo.youtube.$touched, 'is-valid': newvideo.youtube.$valid }" placeholder="Youtube Url" ng-model="videoModel.youtube" name="youtube" ng-pattern="youtubeValidateRegex" required>
<div class="help-block" ng-messages="newvideo.youtube.$error" ng-show="newvideo.youtube.$touched">
<p ng-message="required">YouTube Url is required.</p>
<p ng-message="pattern">Please input a valid YouTube Url.</p>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10" ng-if="!success">
<button class="btn btn-default" ng-click="newVideo(videoModel)" ng-disabled="newvideo.$invalid"> Publish</button>
</div>
</div>
JS
$scope.videoModel = {
youtube: 'https://www.youtube.com/watch?v=VkzVgiYUEIM',
vimeo: 'https://vimeo.com/193391290'
};
$scope.newVideo = function(payload) {
$scope.processing = true;
payload.user = $scope.user._id;
payload.filename = $scope.filename;
console.log(payload);
if(payload.type === 'vimeo') {
var matchVM = payload.vimeo.match($scope.vimeoExtractRegex);
console.log(matchVM);
if(matchVM) { //todo: helpers
payload.vimeo = matchVM[5];
} else {
return toastr.error('Unable to extract Vimeo ID');
}
}
if(payload.type === 'youtube') {
var matchYT = payload.youtube.match($scope.youtubeExtractRegex);
if (matchYT && matchYT[1].length === 11) { //todo: helpers
payload.youtube = matchYT[1];
} else {
return toastr.error('Unable to extract YouTube ID');
}
}
Videos.newVideo(payload)
.then(function(result) {
toastr.success('New video created.');
$scope.processing = false;
$scope.success = true;
$scope.result = result.data.result;
$scope.payload = result.data.payload; //I do assign part of the result to $scope.payload... but that still doesn't explain videoModel.youtube getting overwritten.
})
.catch(function(response) {
$scope.error = true;
toastr.error(response.data.message, response.data.status);
});
return $scope.success;
};

In JavaScript, object references are values.
Because of this, objects will behave like they are passed by reference:
If a function changes an object property, it changes the original value.
Changes to object properties are visible (reflected) outside the function.
http://www.w3schools.com/js/js_function_parameters.asp

I guess by now you might have understood what is pass by value and reference.
Here is a quick solution for you without changing much,you can use angular.copy() which will create new copy of your model into the payload variable and further you can do your rest of processing.
$scope.newVideo = function(videoModel) {
var payload = angular.copy(videoModel)
//do some processing here...
}
Hope this helps you !

Related

Unable to view data on an oservable

I have a View model, which has a loaddata function. It has no constructor. I want it to call the loadData method IF the ID field has a value.
That field is obtained via:
self.TemplateId = ko.observable($("#InputTemplateId").val());
Then, at the end of my ViewModel, I have a bit of code that checks that, and calls my load function:
if (!self.CreateMode()) {
self.loadData();
}
My load method makes a call to my .Net WebAPI method, which returns a slighly complex structure. The structure is a class, with a few fields, and an Array/List. The items in that list, are a few basic fields, and another List/Array. And then THAT object just has a few fields. So, it's 3 levels. An object, with a List of objects, and those objects each have another list of objects...
My WebAPI call is working. I've debugged it, and the data is coming back perfectly.
self.loadData = function () {
$.get("/api/PlateTemplate/Get", { id: self.TemplateId() }).done(function (data) {
self.Data(ko.mapping.fromJS(data));
});
}
I am trying to load the contents of this call, into an observable object called 'Data'. It was declared earlier:
self.Data = ko.observable();
TO load it, and keep everything observable, I am using the Knockout mapping plugin.
self.Data(ko.mapping.fromJS(data));
When I breakpoint on that, I am seeing what I expect in both data (the result of the API call), and self.Data()
self.Data seems to be an observable version of the data that I loaded. All data is there, and it all seems to be right.
I am able to alert the value of one of the fields in the root of the data object:
alert(self.Data().Description());
I'm also able to see a field within the first item in the list.
alert(self.Data().PlateTemplateGroups()[0].Description());
This indicates to me that Data is an observable and contains the data. I think I will later be able to post self.Data back to my API to save/update.
Now, the problems start.
On my View, I am trying to show a field which resides in the root class of my complex item. Something I alerted just above.
<input class="form-control" type="text" placeholder="Template Name" data-bind="value: Data.Description">
I get no error. Yet, the text box is empty.
If I change the code for the input box to be:
data-bind="value: Data().Description()"
Data is displayed. However, I am sitting with an error in the console:
Uncaught TypeError: Unable to process binding "value: function
(){return Data().Description() }" Message: Cannot read property
'Description' of undefined
I think it's due to the view loading, before the data is loaded from the WebAPI call, and therefore, because I am using ko.mapping - the view has no idea what Data().Description() is... and it dies.
Is there a way around this so that I can achieve what I am trying to do? Below is the full ViewModel.
function PlateTemplateViewModel() {
var self = this;
self.TemplateId = ko.observable($("#InputTemplateId").val());
self.CreateMode = ko.observable(!!self.TemplateId() == false);
self.IsComponentEditMode = ko.observable(false);
self.IsDisplayMode = ko.observable(true);
self.CurrentComponent = ko.observable();
self.Data = ko.observable();
self.EditComponent = function (data) {
self.IsComponentEditMode(true);
self.IsDisplayMode(false);
self.CurrentComponent(data);
}
self.loadData = function () {
$.get("/api/PlateTemplate/Get", { id: self.TemplateId() }).done(function (data) {
self.Data(ko.mapping.fromJS(data));
});
}
self.cancel = function () {
window.location.href = "/PlateTemplate/";
};
self.save = function () {
var data = ko.mapping.toJS(self.Data);
$.post("/api/PlateTemplate/Save", data).done(function (result) {
alert(result);
});
};
if (!self.CreateMode()) {
self.loadData();
}
}
$(document).ready(function () {
ko.applyBindings(new PlateTemplateViewModel(), $("#plateTemplate")[0]);
});
Maybe the answer is to do the load inside the ready() function, and pass in data as a parameter? Not sure what happens when I want to create a New item, but I can get to that.
Additionally, when I try save, I notice that even though I might change a field in the view (Update Description, for example), the data in the observed view model (self.Data) doesn't change.
Your input field could be this:
<div data-bind="with: Data">
<input class="form-control" type="text" placeholder="Template Name" data-bind="value: Description">
</div>
I prefer using with as its cleaner and should stop the confusion and issues you were having.
The reason that error is there is because the html is already bound before the data is loaded. So either don't apply bindings until the data is loaded:
$.get("/api/PlateTemplate/Get", { id: self.TemplateId() }).done(function (data) {
self.Data(ko.mapping.fromJS(data));
ko.applyBindings(self, document.getElementById("container"));
});
Or wrap the template with an if, therefore it won't give you this error as Data is undefined originally.
self.Data = ko.observable(); // undefined
<!-- ko if: Data -->
<div data-bind="with: Data">
<input class="form-control" type="text" placeholder="Template Name" data-bind="value: Description">
</div>
<!-- /ko -->
Also if you know what the data model is gonna be, you could default data to this.
self.Data = ko.observable(new Data());
Apply Bindings Method:
var viewModel = null;
$(document).ready(function () {
viewModel = new PlateTemplateViewModel();
viewModel.loadData();
});

If HTML response is null, display alternate content

My api call returns html, but if that html is empty e.g. I get a console html response of "", I want to display a default message using knockout. So I'm guessing that it needs to recognise that "" is empty and then display my alternate content.
View model -
var MyText = ko.observable();
var company = shell.authenticatedCompany();
hazibo.helpTextGet(company.name, company.userName, company.password).then(function (data) {
MyText(data);
});
return {
MyText: MyText
};
View -
<section class="help-text">
<div class="flex-container">
<div class="flex-item" data-bind="html: MyText">This is my alternate message if the html response is ""</div>
</div>
</section>
There are a few ways you could go about it. Personally I like to keep as much code out of the markup as possible so I would check your response data in the api callback and set it there. No need to create messy looking data bindings if you just update the observable appropriately.
hazibo.helpTextGet(company.name, company.userName, company.password).then(function (data) {
if(!data) {
MyText("This is my alternate message...");
}else{
MyText(data);
}
});
If you need to preserve what the api call actually returned you could place the logic in a computed instead, and bind to that.
One way to achieve this is to use a computed observable to determine which set of html to display:
https://jsfiddle.net/dw1284/ucnewzwo/
HTML:
<section class="help-text">
<div class="flex-container">
<div class="flex-item" data-bind="html: ItemHtml()"></div>
</div>
</section>
JavaScript:
function ViewModel() {
var self = this;
// Html populated from API call
self.MyText = ko.observable('');
// Default Html
self.Default = ko.observable('This is my alternate message if the html response is ""');
// Computed observable chooses which HTML to display (bind this to view)
self.ItemHtml = ko.computed(function() {
if (!self.MyText() || self.MyText() === '') {
return self.Default();
} else {
return self.MyText();
}
});
}
ko.applyBindings(new ViewModel());

Can I make one object have the same order as another object?

I know that the title of this question already doesn't make sense because objects are unordered by their nature. BUT, I think if you take a look at this screen shot that's linked here, it'll make more sense.
Picture of the two objects in my console.log
Here is what's happening. I am creating an object called $scope.gameConfigs, which is itself created from data I receive from a server call (a provisions object). This $scope.gameConfigs creates a group of dropdown menus.
Basically what I'm trying to do is make the dropdown menus display previously saved data IF the data exists. When saved data exists, the server returns an object that has all the saved data. This data is ordered numerically. My problem is, this saved data is not always ordered the same as the data in the $scope.gameConfigs I create, which results in blank fields appearing in my dropdowns.
If you look at the screenshot I linked to, you can see that the keys in $scope.gameConfigs (the object with line 30 written next to it) are Map, Server, and Mode.
The second object, which is the saved data returned from the server, is a group of objects that each have a name property (which is the name of the dropdown menu). If you take a look at that, the order is Server, Map, and Mode.
My question is, how can I make the Saved Data object copy the order of my $scope.gameConfigs object? Is that even possible? If not, what would be the best way to proceed?
Here is the HTML and the controller I have for my page/controller, too, if that helps at all:
<form class="form-horizontal" ng-controller="GamePreferenceCtrl">
<div ng-repeat="(name, section) in gameConfigs">
<label ng-bind="name"></label>
<select class="form-control" ng-model="formData.settings[$index].value" ng-change="dropdownItemClicked(name, formData.settings[$index].value)">
<option value="" disabled="disabled">---Please Select Option---</option>
<option ng-repeat="item in section" value="{{item.value}}" ng-bind="item.value"></option>
</select>
</div>
<div class="col-md-12" ng-include="gametemp"></div>
<div class="row">
<div class="hr-line-dashed"></div>
<div class="text-center col-md-12 padding-15">
<button class="btn btn-primary btn-lg" ng-click="saveGameSetting()" formnovalidate translate>
<i class='fa fa-circle-o-notch fa-spin' ng-if="showBusy"></i> Save
</button>
</div>
</div>
</form>
and the controller:
function GamePreferenceCtrl($scope, $filter, Tournament, Notification) {
$scope.$parent.child.game = $scope;
$scope.selectedItems = [];
$scope.formData = {};
$scope.loadConfig = function () {
Tournament.loadGameConfig($scope.id).then(function (response) {
$scope.gameConfigs = {};
if (response.data.tournamentPrefs) {
_.each(response.data.tournamentPrefs, function (val) {
if ($scope.formData.settings === undefined) {
$scope.formData.settings = [];
}
$scope.formData.settings.push({section: val.name, value: val.value});
});
$scope.formData = {};
};
$scope.dropdownItemClicked = function(name, value) {
if($scope.formData.settings === undefined) {
$scope.formData.settings = {};
$scope.formData.settings[name] = value;
} else {
console.log('inside else');
$scope.formData.settings[name] = value;
}
};
_.each(response.data.provisions, function (val) {
if ($scope.gameConfigs[val.section] === undefined) {
$scope.gameConfigs[val.section] = [];
}
$scope.gameConfigs[val.section].push({name: val.key, value: val.value});
});
});
};
I know this is a long read, and I truly appreciate anyone who might be able to help me out with this. Thank you!
You may do like
var o = {z:1, f:2, a:7}
p = Object.assign({},o),
q = Object.assign(o)
console.log(o, p, o === p);
console.log(o, q, o === q);

Updating a value in an array using a function - Angular JS

I'm relatively new to AngularJS and I've found myself slightly confused.
Here is my controller:
app.controller("calcController", function($scope) {
$scope.interests=[{time:'month',amount:0},
{time:'quarter',amount:0},
{time:'year',amount:0}];
$scope.rates=[{rate:0.01,lower:0,upper:1000,desc:'£0 - £1000'},
{rate:0.02,lower:1000,upper:5000,desc:'£1000 - £5000'},
{rate:0.03,lower:5000,upper:'none',desc:'£5000+'},];
$scope.balance=0;
$scope.updatedIntAmount=function(balance){
if(balance<0){
return 0;
}
else if(balance>=rates[1].lower && balance<rates[1].upper){
return balance*rates[1].rate;
}
else if(balance>=rates[2].lower && balance<rates[2].upper){
return balance*rates[2].rate;
}
else {
return balance*rates[3].rate;
}
}
});
What I want is some way to bind the value of interests.amount to updatedIntAmount.
Here's my HTML:
<div ng-controller="calcController" class="container">
<div class="form-group">
<label for="balInput">Balance:</label>
<input id="balInput" type="text" class="form-control" ng-model="balance">
</div>
<p ng-repeat="interest in interests">{{'per '+interest.time+':'+interest.amount}}</p>
</div>
So what I have is interests.amount dependent on calculateIntAmount, which in turn is dependent on both rates.rate and balance. How can I get these interests.amount values to change whenever balance is updated?
Thanks
Try adding ng-change to your input field like so <input id="balInput" type="text" class="form-control" ng-model="balance" ng-change="updatedIntAmount(balance)">. This will allow you to call the function on a change to the input field and thus do whatever you want within the function in your controller.
You can learn more at the official AngularJS documentation page
You can look into using $scope.$watch to observe any changes in your balance variable, and then update your interests.amount accordingly.
In your controller, you would have:
$scope.$watch('balance', function(newBalance) {
$scope.interests.amount = $scope.updatedIntAmount(newBalance);
});
Lot of errors are present in your code.
as first there is nothing like rates[1] instead you should change it to $scope.rates[1].
Second : your updatedIntAmount function contains rates[3] which is again wrong as you have rates[2] as max limit according to array index rule.
Your updatedIntAmount function return a single value based upon the balance is inserted. in that case after correcting the errors just add :
{{updatedIntAmount(balance)}}
in your html code. it will change as soon as change in balance.
$scope.updatedIntAmount=function(balance){
if(balance<0){
return 0;
}
else if(balance>=$scope.rates[0].lower && balance<$scope.rates[0].upper){
return balance*$scope.rates[0].rate;
}
else if(balance>=$scope.rates[1].lower && balance<$scope.rates[1].upper){
return balance*$scope.rates[1].rate;
}
else {
return balance*$scope.rates[2].rate;
}
}

Updating multi-model form from Angular to Sinatra

I'm currently having an issue with updating a form in Angular and pushing the update through to Sinatra.
It is supposed to:
When clicked, the form to edit the current item is shown (current data for each field is displayed from the item scope).
When submitted, it is attempting to update to a different scope (updateinfo). I am not sure but do I need a way of using multiscope or one scope to allow it to update?
At present the script sends the correct downloadID parameter, but the JSON from the scope submitted is as I believe, incorrect.
Also, I'm not sure whether the Sinatra app.rb syntax is correct, for someone new to these frameworks, it has been hard to find useful documentation online.
If anybody could help it would be very much appreciated.
downloads.html
<div ng-show="showEdit">
<form ng-submit="updateinfo(item.downloadID); showDetails = ! showDetails;">
<div class="input-group"><label name="title">Title</label><input type="text"
ng-model="item.title"
value="{{item.title}}"/></div>
<div class="input-group"><label name="caption">Download caption</label><input type="text"
ng-model="item.caption"
value="{{item.caption}}"/>
</div>
<div class="input-group"><label name="dlLink">Download link</label><input type="url"
ng-model="item.dlLink"
value="{{item.dlLink}}"/>
</div>
<div class="input-group"><label name="imgSrc">Image source</label><input type="url"
ng-model="item.imgSrc"
value="{{item.imgSrc}}"/>
</div>
<!-- download live input types need to be parsed as integers to avoid 500 internal server error -->
<div class="input-group"><label name="imgSrc">
<label name="dlLive">Download live</label><input type="radio" ng-model="download.dl_live"
value="1"/>
<label name="dlLive">Not live</label><input type="radio" ng-model="download.dl_live"
value="0"/></div>
<div class="input-group"><label name="imgSrc"><input type="submit"/></div>
</form>
controllers.js
$scope.loadData = function () {
$http.get('/view1/downloadData').success(function (data) {
$scope.items = data;
});
};
$scope.loadData();
$scope.updateinfo = function(downloadID) {
id = downloadID
var result = $scope.items.filter(function( items ) {
return items.downloadID == id;
});
console.log(result);
updatedata = $scope.items
$http({
method : 'PUT',
url : '/view1/downloadedit/:downloadID',
data : result
});
};
app.rb
#edit download
put '/view1/downloadedit' do
puts 'angular connection working'
ng_params = JSON.parse(request.body.read)
puts ng_params
#download = Download.update(ng_params)
end
The wrong scope was attempting to be used. Once the scope was corrected to items, the correct JSON was being routed:
$scope.updateinfo = function(downloadID) {
id = downloadID
var result = $scope.items.filter(function( items ) {
return items.downloadID == id;
});
console.log(result);
updatedata = $scope.items
$http({
method : 'PUT',
url : '/view1/downloadedit/:downloadID',
data : result
});

Categories

Resources