I would like to pass an object to a controllerA to another controllerB and display that object. To do it, I'm using ui-router with angularjs.
This is my controllerA which build the URL using $state.href():
const url = $state.href('home.stateA', {
objectA: objectA
});
window.open(url, '_blank');
Now, this my route file:
.state('home.stateA', {
url: '/stateA',
template: '<template-b></template-b>',
params: {
// object: null
objectA: null
}
})
And finnaly, I try to get my object in my controllerB like that:
// $scope.object = $stateParams.object;
$scope.object = $stateParams.objectA;
When I console.log $scope.object, I'm getting null which is the default value in my route file.
So what's going wrong ? I'm wondering if $window.open would not be the problem.
Thanks for helping me.
window.open(url, '_blank');
You are opening a new window and trying to pass an object.
Passing a String/Number
You can pass a string/number say id, as part of the URL, if your state URL is defined like '/stateUrl/:id'
and then you can access this using $stateParams.id
Sharing an object
You can use localStorage along with JSON.stringify and JSON.parse to share the object.
Set data
localStorage.setItem('object', JSON.stringify(object));
Get data
var object = JSON.parse(localStorage.getItem('object'));
I have just found the solution ->
ControllerA
const url = $state.href('stateA');
let newTab = $window.open(url);
newTab.objectA = objectA;
ControllerB:
$scope.objectA = $window.objectA
And the state is very simple :
.state('home.stateA', {
url: '/stateA',
template: '<template-b></template-b>',
})
I don't know if it's the best way to implement what I needed but at least it works. it may help someone else.
Thanks guys and have a nice day !
I suggest you use url parameter.
.state('home.stateA', {
url: '/stateA?object',
template: '<template-b></template-b>',
params: {
object: null
}
})
Do when open new tab page
const url = $state.href('home.stateA', {
objectA: JSON.stringify(objectA)
});
In controllerB
$scope.object = JSON.parse($stateParams.objectA);
Because when you are open new tab. The state param is lost
Related
I have passed props through to different components and pages before but this has been through link or just added these to the component tag itself.
The issue I have here is that the redirect is not going through a link tag or in a component tag and instead I am simply using window.locatio.href ="whatever the url is".
I simply want to pass a variable through to this (I am technically doing a refresh in this situation so window.location.reload() could also work if it is possible).
How would I pass through a variable within this.
When using express you can do fetch statements with an endpoint simialr to (might not be exact syntax) "./page${variableYouWant}" Then access sit in the express file using req.params.variableYouWant.
Is this possible to pass a variable this way and how would I then access it.
Here is the most important snippet of my code.
pageRelocator(mssg) {
if (mssg.length < 35) {
toast.info(`${mssg}`, {
draggable: true,
autoClose: 1500
});
window.location.href = "http://localhost:3000/completed-assessment";
} else if (mssg.length > 35) {
toast.error(`${mssg}`, {
draggable: true,
autoClose: 1500
});
//Here I would like to pass a variable
window.location.href = "http://localhost:3000/user-questions";
}
}
EDIT--
componentDidMount() {
const search = this.props.location.mssg;
alert(search); // returns the URL query String
const params = new URLSearchParams(search);
const IdFromURL = params.get("mssg");
this.setState({
questions: this.getItems(),
WorkStations: this.getWorkStations()
});
}
pageRelocator(mssg) {
if (mssg.length < 35) {
window.location.href = "http://localhost:3000/completed-assessment";
} else if (mssg.length > 35) {
window.location.href = `http://localhost:3000/user-questions?mssg=${mssg}`;
}
}
Try using the URLSearchParams which defines utility methods to work with the query string of URL.so to attach a variable you would do
var id=5;
window.location.href = `http://localhost:3000/user-questions?id=${id}`;
and to retreive id from the URL you would do
const search = props.location.search; // returns the URL query String
const params = new URLSearchParams(search);
const IdFromURL = params.get('id');
Hope this helps
If you want the data to be present even after refresh, try to pass the variable in params.
http://localhost:3000/completed-assessment?your_variable=value
If you want to use this params value you can use
window.location.search
Using URLSearchParams you can get the each params you've sent with the URL.
Please refer https://www.sitepoint.com/get-url-parameters-with-javascript/ for more info
I'm trying to JSON.stringify() the model of a route inside the controller by using the below code. It works and it returns all model attributes, except for the actual id of the model. Can we receive the id as well?
var plan = this.get('model');
var reqBody = JSON.stringify(
{
plan,
token
});
You need to pass in the includeId option to the toJSON method in order to get the ID in the JSON.
var plan = this.get('model');
var reqBody = JSON.stringify({
plan: plan.toJSON({ includeId: true }),
token
});
And if you didn't know, JSON.stringify() will call toJSON() for you (which is what is happening in your case). If you want to call JSON.stringify() instead of model.toJSON({}), you can always override it:
App.Plan = DS.Model.extend({
toJSON: function() {
return this._super({ includeId: true });
}
});
That way JSON.stringify(plan) will give you exactly what you want.
In the code below, the fetch() and sync() methods are not doing anything.
I am trying to see how the data in my localStorage gets updated and the methods are not updating it (example LS string is in the code)
Where am I going wrong?
function makeWorkingLS(collDesc, projDesc, Id, Description, ElapsedSeconds, ElapsedTime, WorkItemType){
//Create observable object from params
var activeTaskObject = kendo.observable ({
client: collDesc,
project: projDesc,
taskId: Id,
description: Description,
elapsedSeconds: ElapsedSeconds,
elapsedTime: ElapsedTime,
comment: WorkItemType
});
// example string in localStorage:
//{"client":"Morken Mindy","project":"Shazbat creation engine","taskId":183,"description":"Create the Shazbat 100% efficiency engine","elapsedSeconds":296803,"elapsedTime":"82h43m","comment":"Task"}
// Convert to JSON string for localStorage
var activeTask = JSON.stringify(activeTaskObject);
console.info(activeTask);
//Write to localStorage
window.localStorage.setItem("activeTask",activeTask);
//Set it as the active datasource for updating to webservice
var activeTaskDS = new kendo.data.DataSource({
transport: {
read: function(options){
taskItem = JSON.parse(localStorage["activeTask"]);
},
update: {
url: remUpd, //url var declared earlier in the process
dataType: "json"
}
},
schema: {
model: {
client: "client",
taskId: "taskId"
},
data: function(){
return taskItem;
}
}
});
activeTaskDS.fetch(function(){
activeTaskDS.data()[0].set("client", "NOBODY");
activeTaskDS.sync();
cosole.log("activeTaskDS.data()[0] : "+activeTaskDS.data()[0]); //should read 'NOBODY' but reads 'Morken Mindy'
});
}
Thanks in advance,
Neil.
I'm not sure what is the problem actually, but I have to point some important things:
AFAIK, when you customize any transport methods you have to pass the data into a callback in the options object:
transport: {
read: function(options){
taskItem = JSON.parse(localStorage["activeTask"]);
// Tells the widget to handle that collection
options.success(taskItem);
}
}
In schema.data it seems that you want to pass your data through this method(correct me if I'm wrong). But this method isn't for that purpose. It is used just to tell the widget which field to read(in case of passing a string to it) or to read a property from a response, which comes as a parameter that you are not using. Check the second example here. So this may not be right way to read the taskItem object as data;
Speaking about the taskItem object, it seems that its the base data of your dataSource but it isn't defined(at least on the snippet you posted). What I mean is, if you follow the step 1 you won't even need to read from that object no more.
Please let me know if this is helpful and if you need anyting more.
I am using store plugin of annotator.js
The problem is I am not able to store the received data(enetered into the comment box of annotatorjs ) at the desired location as JSON.
The code for the plugin is as follows
$('#page-container').annotator().annotator('addPlugin', 'Store', {
urls: {
prefix: '/editor/uploaded',
update:'/annotations',
}
});
The output I get in console is
XHR finished loading: POST "http://localhost/editor/uploaded/annotations"
Uncaught TypeError: Cannot read property 'id' of null
Please let me know how the storage can be accomplished.
Thanks in advance !!
You are building the object passed as parameter wrong, as "prefix" is not a property inside "urls".
Regarding your example, the right way would be:
$('#page-container').annotator().annotator('addPlugin', 'Store', {
prefix: '/editor/uploaded',
urls: {
update:'/annotations'
}
});
Then you need to set up the API on the server side, as required by the plugin.
Personally, I ended up creating my own store plugin, so I could process annotations exactly as I needed. It's not very hard and it's really worth the effort.
public annotatorFunc(): void {
const pageUri = function () {
return {
beforeAnnotationCreated: function (ann) {
ann.uri = window.location.href;
}
};
};
const elem = document.querySelector('pdf-container');
const app = new annotator.App();
app.include(annotator.ui.main, {element: elem});
app.include(annotator.storage.http, {prefix: 'http://localhost:8080/api'});
app.include(pageUri);
app.start().then(function () {
app.annotations.load({uri: window.location.href});
});
}
I need to access the parameters of the current url with Durandal.
Actually from the activate function, I'm able to do so:
function activate(routeData) {
var type = routeData.type;
var id = parseInt(routeData.id);
}
and retrieve the following parameters project and 1 of my url:
http://localhost:3231/#/next/project/1
But how can I do so from another function within my view model?
NB: I need also to retrieve next from the url.
var params = window.location.hash.split('/');
Define an action param in your router.map function
something like:
router.map([
{ route: '', title:'Your title', moduleId: ':action/project/:id', nav: true }
])
So you can access the value in your activate function via
routeData.action