Why angularjs change variables that are different? - html

I am getting an ajax data from api and saving it to a variable. And I have to "edit and save" or "edit and cancel" changes on this data. I am using ng-model to show and edit this data.
Here is my script:
function getData() {
$http({
method: 'POST',
url: API + '/api/Educations/UserEducations',
data: {}
}).then(function successCallback(response) {
vm.UserData = response.data;
vm.CachedUserData = response.data;
})
}
And here is my html:
<div ng-repeat="education in editEducationsCtrl.UserData">
<div>{{education.SchoolName}}</div>
<input type="text" ng-model="education.SchoolName">
<button ng-click="editEducationsCtrl.saveChanges()">Save</button>
<button ng-click="editEducationsCtrl.cancelChanges()">Cancel</button>
</div>
When user clicked cancel button, I want to write html cached data.
But,
When I try to access vm.CachedUserData variable, I am seeing this cached data has already changed with new value of vm.UserData... How? I have checked my code there is no function access CachedUserData variable. Even I changed variable name to unique name but result is same.
I want to save first data in a variable. But angular changes both of them. Is 2 way databinding change all variables that connected the same ajax data?

I recommend you to use angular.copy() to bind the data you want to cache:
vm.UserData = response.data;
vm.CachedUserData = angular.copy(response.data);

= in JavaScript does not clone the variable, it creates another pointer on it. That means you can handle your variable by using both vm.UserData and vm.CachedUserData.
It seems you want to clone your variable, so:
If it is an array:
...
}).then(function successCallback(response) {
vm.UserData = response.data.splice(0);
vm.CachedUserData = response.data.splice(0);
})
...
If it is an object:
var newObject = jQuery.extend({}, oldObject); if you have JQuery
obj = JSON.parse(JSON.stringify(o)); without JQuery
Here is a good link for cloning objects in JS.

Related

Sending variable and image via ajax

Could anybody please help me with this as i have tried several different methods all to no avail.
im trying to send the old image src name along with the new image data via ajax, but i can only manage to send 1 or the other and not both..
file = input.files[0];
newimagesrc=input.files[0].name;
oldimagesrc=oldsrc;
formData= new FormData();
formData.append("image", file , newimagesrc);
recent attempt failed formData2= new FormData();
recent attempt failed formdata2.append('oldimage', oldimagesrc);
$.ajax({
url: "UploadProfileImage.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(messagereturn1){
alert(messagereturn1);
}
});
No buttons or forms im afraid, strictly passing variable's onchange / onclick.
Not sure how to send the old image src through ajax as well as the new image data , i would like to send more variables if possible that have been passed into JS function..
var form_data = new FormData(); // Creating object of FormData class
form_data.append("image", file , newimagesrc) // Appending image parameter
form_data.append("oldimagesrc", oldimagesrc) //added a second variable then received in PHP as a $_POST['oldimagesrc']
PHP
if (isset($_POST['oldimagesrc'])){ $oldimagesrc=$_POST['oldimagesrc']; }

how to send a Json object to a dialog from the parent using dialog API in Office365

I am new to office 365 word JavaScript API. I am trying to send a Json object to a dialog from the parent using the dialog api. But I couldn't find a better solution for that. I have found it is possible to send a Json object from the dialog to the parent using below code snippet.
Office.context.ui.messageParent
can someone give me a good solution with a code snippet to solve this problem?
You can try something like that
In parent web page (the actual add-in) javascript code
Office.context.ui.displayDialogAsync(url, options, function(result) {
var dialog = result.value;
dialog.addEventHandler(Office.EventType.DialogMessageReceived, function(args){
dialog.close();
var json = JSON.parse(args.message);
//do what ever you need to do...
});
});
NOTE: for the sake of simplicity I omitted "error checks" if callback function receive error result. You should take care of that as well.
The web page that is opened at url will have a function for pushing back the json object after representing it as a string
var asString = JSON.stringify(myObj);
Office.context.ui.messageParent(asString);
Of course the webpage opened in the dialog window must also reference Office.js.
Here is the documentation link for this so-called dialogAPI https://dev.office.com/reference/add-ins/shared/officeui
Edit:
the original question is to send data from parent to children
If you need to send info to the page opened in dialogAPI. I suggest your append query parameters to url. You can stringify your Json object and pass it. This is not very clean thought.
Standardized way to serialize JSON to query string?
You can send JSON data or object back to your parent easily.
This code snippet should be in your child page's(Dialog page) JS file.
(function () {
"use strict";
// The Office initialize function must be run each time a new page is loaded
Office.initialize = function (reason) {
$(document).ready(function () {
$('#btnLogin').click(submit);
});
};
function submit() {
// Get and create the data object.
var email = $('#txtEmail').val();
var password = $('#txtPassword').val();
var data = {
email: email,
password: password
}
// Create the JSON and send it to the parent.
var json = JSON.stringify(data);
Office.context.ui.messageParent("json");
}
})();
See here: https://dev.office.com/docs/add-ins/develop/dialog-api-in-office-add-ins
Find section "Passing information to the dialog box".
Two primary ways:
Add query parameters to the URL
Store the information somewhere that is accessible to both the host window and dialog box, e.g. local storage

How to create an angular form that uses session storage that can be called throughout the html pages

I want to create a form on an index page that can store data via session storage. I also want to make sure that whatever data(let's say name) ... is remembered and used throughout the site with angular. I have researched pieces of this process but I do not understand how to write it or really even what it's called.
Any help in the right direction would be useful as I am in the infant stages of all of this angular business. Let me know.
The service you want is angular-local-storage.
Just configure it in your app.js file:
localStorageServiceProvider
.setStorageType('sessionStorage');
And then use it in the controller that contains whatever data you want to remember. Here is an example of a controller that loads the session storage data on initialization, and saves it when a user fires $scope.doSearch through the UI. This should give you a good place to start.
(function () {
angular.module("pstat")
.controller("homeCtrl", homeCtrl);
homeCtrl.$inject = ['$log', 'dataService', 'localStorageService', '$http'];
function homeCtrl ($log, dataService, localStorageService, $http) { {
if (localStorageService.get("query")) { //Returns null for missing 'query' cookie
//Or store the results directly if they aren't too large
//Do something with your saved query on page load, probably get data
//Example:
dataService.getData(query)
.success( function (data) {})
.error( function (err) {})
}
$scope.doSearch = function (query) {
vm.token = localStorageService.set("query", query);
//Then actually do your search
}
})
}()

Change html page with jqm (1.4.0), passing parameter

I am building several apps and want to be able to reuse som code as separate HTML pages by passing parameters to them.
I would really like to pass parameters via ajax with one of these:
Alt1
$.mobile.pageContainer.pagecontainer("change", "../Photo/Photo.html", { reload: true, parameter: "dummyParameter"});
$.mobile.changePage("../Photo/Photo.html", { reloadPage: true, parameter: "dummyParameter"});
Problem is that the page wont reload.
If I use the below link the page is loaded/reloaded, but I cant seem to find the passed parameter.
Alt2
Or through a basic link
(I would prefeer to not generate the url in javascript as in alt2 but if what it takes...)
I use this code to try to retreive the parameters:
$(document).on("pagebeforechange", function (e, data) {
if (data.toPage[0].id == "Photo") {
//var parameters = $(this).data("url").split("?")[1];
//var parameter = parameters.replace("paremeter=", "");
var stuff = data.options.stuff;
//showStuff("#p2", stuff);
}
});
While I'm at it, if someone uses type script. Visual studio complains about that this call signature isnt correct:
$(document).on("pagebeforechange", function (e, data)
Expects one argument, the event, not the data. The plugin generates correct javascript but the IDE complains.
Thanks!

How to show html files with modal.open using jquery?

Currently i use a fine working code for opening a modal with Jquery :
$(document).ready(function(){
$("span.ico-detail").click(function(){
modal.open({content: "View detail of " + $(this).parent().parent().attr("id")});
e.preventDefault();
});
});
And now the problem is : How can I use modal.open to open a HTML file named "view.html", which contaning the string of "View detail of "?
What should I change the content : "xxx" with, so I can open the HTML file (view.html) and join it with other text ?
Thanks before.
If the view.html is stored on a server and its content is static, then you can choose to preload the content of the file using ajax.
$(function () {
window.myAppNs = {
viewContent: null;
};
$.ajax({
url: 'view.html',
dataType: 'html',
type: 'GET'
}).done(function (resp) {
myAppNs.viewContent = resp;
});
$("span.ico-detail").click(function(){
modal.open({content: myAppNs.viewContent + $(this).parent().parent().attr("id")});
e.preventDefault();
});
});
I am creating a global variable myAppNs. This will hold all app related variables. The idea is not pollute the global namespace with unnecessary variables. There are better and safer ways to create a namespace. If that interests you, you can google for the same.
The ajax call preloads the content of the view.html and stores it in myAppNs.viewContent. The click handler reads that content from the variable.
There is a slight chance that the user can click the element before the ajax response is returned. If that's an issue, you can always move the namespace creation and ajax call out of document.ready and place it in the head section, immediately after referencing jquery. That ought to give the browser enough time to fetch the content before the dom is ready, but there is still that small possibility that the response might be delayed. If you need to ensure the user can click only if the data has been fetched, then bind the click handler inside the done callback of the ajax call.