Reputation: 163
How I can pass object from page to page with $stateProvider in angularjs? Can you give me some code snippet? I'm new in angular
Thanks in advance
Upvotes: 0
Views: 849
Reputation: 163
I solved issue, the problem was in version of angular-ui-router, it jsut didn't work with version that I had, to be more concrete I got error when I try to add params on state
Upvotes: 0
Reputation: 38
If you're looking to "pass" objects only between a few (e.g., two or three) views, then using $stateProvider
would suffice. However, if the same objects shall be retrieved/modified by several different parts of the application, it would be better to place these objects in a service.
For instance, a factory may be created to store such an object.
(function () {
angular.module('myApp').
factory('myFactory', myFactory);
function myFactory() {
var object ={};
var service = {
getObject: getObject,
setObject: setObject,
setObjectProperty: setObjectProperty
};
return service;
function getObject() {
return object
}
function setObject(newObject) {
//Some modification logic here
object = newObject;
return object;
}
function setObjectProperty(property, value) {
//Modify/assign new object property here
return object;
}
}
})();
A controller can then use the factory to retrieve/modify the stored object.
(function () {
angular.module('myApp').
controller('MyController', MyController);
function MyController(myFactory) {
var vm = this,
someObject = { ... };
//Invoke public factory functions
vm.object = myFactory.setObject(someObject);
}
})();
Upvotes: 0
Reputation: 56956
You don't pass the object, you pass the object's ID which will allow you to retrieve the object.
You should use ui-router for this.
When definining states you will define the URL as something like ...
"url": '/an/example/path/:objectid',
"controller": "YourControllerForThisView",
USE OF THE COLON DEFINES THAT THIS IS A VARIABLE PARAMETER
Then in your controller you can access
state.params.objectid
Then in your controller you will call a method like ...
myService.getObjectFromList(state.params.objectid)
OR
myService.getObjectFromHttpCall(state.params.objectid)
to populate the object to be used when rendering the view
Hope this helps
Upvotes: 0
Reputation: 2078
When defining a state you have a few options:
.state('my-state', {
url: '/my-state',
templateUrl: 'my-state-url',
params: {
myProperty: 'some value',
}
})
Then you can do this while changing state:
$state.go('my-state', {myProperty: 'new value'});
In the state controller you can access the myProperty
like so:
$scope.myProperty = $stateParams.myProperty;
But depending on the data you want to pass, a custom angular service can/should be used. There's a good tutorial regarding this subject here.
Upvotes: 1