I have a partial from which I need to call a route which will have a controller and a view of its own. When I call the route, I also need to pass a json object to the controller. I have done this earlier for simple values like id, name etc but in that case, I passed it as path param and I can retrieve it using the $routeparams. But how to do the same with json object. Please let me know.
You could use a factory to save data from one controller and retrieve it from an other controller.
Something like this?
angular.module('app')
.factory('mySerivce', function() {
var jsonData;
return {
setData: function(data) {
jsonData = data;
},
getData: function() {
return jsonData;
}
}
});
setData from the first controller and from the second getData.
Related
Here coupon is the my ng-model passing parameter from controllers. i getting the response data. i dont know how to get the this response from factory to services.
please help me..
var factmodule=angular.module("FactModule",["ngResource"]);
factmodule.factory("CouponFactory",function($resource){
var couponinfo;
var coupondata
return{
getcoupon:function(coupon){
var user=$resource("http://demo.foodzard.in/api/promocode?code="+coupon.offer);
user.get(function(data){
couponvalue=data
console.log(data);
return couponvalue;
})
}
}
})
Services code
var servctrl=angular.module("ServModule",["FactModule"]);
servctrl.service("CouponService",function(CouponFactory){
this.checkdata=function(coupon){
CouponFactory.getcoupon(coupon)
}
})
controllers code
// getting coupon code from ng-model in the text box
mainCtrl.controller("OrderController",function($scope,CouponService){
$scope.validate=function($scope.coupon){
CouponService.checkdata($scope.coupon)
}
});
If factmodule is in a separate module from servctrl then you need to inject the factmodule into the servctrl on creation of the angular module
e.g.
var servctl = angular.module('servctl', [
'factmodule']);
})();
what I would be doing is
app.factory("CouponFactory",function($resource){...
and
app.service("CouponService",function(CouponFactory){
Then they are in the same module and would be reachable
It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data.1
Since the return couponvalue; statement occurs in a function that the $q service invokes in the future, the factory function which executes immediately does not return any data.
Instead return the empty user reference and use its $promise property to retrieve the data.
var factmodule=angular.module("FactModule",["ngResource"]);
factmodule.factory("CouponFactory",function($resource){
var couponinfo;
var coupondata
return {
getcoupon:function(coupon){
var user=$resource("http://demo.foodzard.in/api/promocode?code="+coupon.offer);
//return object reference
return user.get();
}
}
})
Use $promise property to retrieve data from the $q service.
var servctrl=angular.module("ServModule",["FactModule"]);
servctrl.service("CouponService",function(CouponFactory){
this.checkdata=function(coupon){
return resourceObject = CouponFactory.getcoupon(coupon);
//retrieve future data
resourceObject.$promise.then( onFullfilled(data) {
var couponvalue=data;
console.log(data);
});
});
});
The .then method of a promise takes a function as an argument. The $q service stores that function and invokes it in the future when the XHR completes.
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
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.
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
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);
}
})();
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
So here's my general problem, I have a factory which needs to make an ajax call to get its value. I want to inject this factory, but only after the ajax call has been resolved, meaning, when it's injected, I want the value to already be there. Is this possible? Let me give you some context so you can maybe give me a better option.
I have a UserFactory.
var app = angular.module('app',[]);
app.factory('UserFactory',[
function(){
//ajax call to get the user object
//dont allow injection until user has arrived
}
]);
var home = angular.module('home',[]);
home.controller('UserInfoController',[
'UserFactory',//I don't want this resolved until the ajax call has completed
function(User){
//bind user data to the view
}
]);
Is this possible? Or am I going about this wrong? I want to be able to access the user's information without having to use promises every time, just in case it's not already there.
What you can do is set up your factory so that it remembers the user data.
Something like this
app.factory('userFactory', function ($http){
return {
getUser: function(){
return $http({
method: 'GET',
url: ''
});
},
currentUser: {}
};
});
So then in your controller, check to see if there is anything in currentUser. If not make the getUser call and store it into currentUser. Since the factory is a singleton the userdata will always exists inside this factory and you can inject it anywhere you need it.
Here's an example: http://jsfiddle.net/4m6gmsw2/
If you still need the user data to be there before injecting it you can take a look at using resolve: https://thinkster.io/egghead/resolve/
In the state router, there is resolve property for each state.
.state({
name: 'myState',
resolve: {
user: function(myService) {
return myService.asyncGet();
}
}
Then in your controller:
.controller('myController', function(user) {
$scope.myData = user.data; //no messy promises
});
I am new to angular so it is probably easy question. I have this factory resource at the moment:
angular.module('resources.survey', ['ngResource'])
.factory('Survey', function ($resource) {
return $resource('/backend/surveys/:surveyId/data', {surveyId: '#id'});
});
Controller:
.controller('PagesCtrl', function (Survey) {
var survey = Survey.get({surveyId: 2});
//now I want to change survey variable and share it between two controllers
});
There are no problems with ngResource I can get the data from server. However I want to manipulate with the data from the server and use the same data in other controllers (probably using DI) and allow data manipulation there as well. I know that it can be done with $rootScope, but I was wondering if there is any other way.
Your service should cache the response for the resource request in something like array of surveys and dispense surveys from this array instead of directly returning a resource object.
Controllers would only share data if the same reference for the survey is returned.
Roughly it would look like
.factory('Survey', function ($resource,$q) {
var surveys[];
return {
getSurvey:function(id) {
var defer=$q.defer();
//if survery contains the survey with id do //defer.resolve(survey[i]);
// else query using resource. On getting the survey add it to surveys result and resolve to the newly added survey.
}
}
});
angular.module('resources.survey', ['ngResource'])
.factory('Survey', function ($resource) {
return $resource('/backend/surveys/:surveyId/data', {surveyId: '#id'});
})
.controller('MyCtrl', function($scope,Survey){
//here you can call all the $resource stuff
});
Here is complete documentation and example how to use it:
http://docs.angularjs.org/api/ngResource.$resource
I managed to create a resource that can handle what I wanted. It is probably not as advanced as Chandermani suggested. But it works for my needs.
angular.module('resources.survey', ['ngResource'])
.factory('Survey', function ($resource) {
var resource = $resource('/backend/surveys/:surveyId/data',
{surveyId: '#id'}
);
var Survey = {};
var data = []; //saves the data from server
Survey.get = function(surveyId) {
if(angular.isDefined(data[surveyId])){
return data[surveyId];
}
return data[surveyId] = resource.get({surveyId: surveyId});
};
return Survey;
});
And to call basically I call it like this:
.controller('QuestionsCtrl', function (Survey) {
Survey.get(1).newData = 'newData'; //adding additional data
console.log(Survey.get(1));
});
I guess this can be improved.
I am new to Angular, and am having an issue where my $http url placeholders are not being replaced by the actual data. What I want is for this:
"/json/:searchType/:userId"
To be replaced with this when I use my $http call:
"/json/user/123"
Instead, I get something like this, according to firebug's Net tab:
"/json/:searchType/:userId?userId=123&searchType=user"
I have tried to create a fiddle, but because I use different views and json data from a server, I'm not sure how to create something that works in the fiddle that still looks anything like what I am actually doing. I have looked at this answer, this answer, this answer, this answer, and this answer, to name a few. I'm having trouble finding a posting that isn't about $resource, or the # notation it uses to link url params to object params though.
To explain, I'm using a service to pass the searchType and accountId params between controllers and my factory, which actually performs the $http request.
Here is my controller:
.controller('UserDetailsCtrl', ["$scope", "Search", function ($scope, Search) {
$scope.result = Search.getUser();
}])
Here is my Factory:
.factory('Search', ["$http", "SearchCriteriaSvc", function($http, SearchCriteriaSvc) {
var baseUrl = "/json/:searchType/:accountId";
return {
getUser: function () {
return $http.get(baseUrl,
{params:
{
accountId: SearchCriteriaSvc.getAccountId(),
searchType: SearchCriteriaSvc.getSearchType()
}
})
.then(function(result) {
return result.data;
});
}
}
}])
Finally, my service:
.service('SearchCriteriaSvc', function() {
var searchType = "",
userId = "";
return {
getSearchType: function () {
return searchType;
},
setSearchType: function(value) {
searchType = value;
},
getUserId: function () {
return userId;
},
setUserId: function(value) {
userId= value;
}
};
})
I have tried not using the service to pass the params (just manually typing in strings) and I get the same result, so I don't think that my service is the issue, but then, I'm at a loss.
Any help would be great. Thanks!
$http doesn't work in that way. You will have to collate your parameters into a URL yourself.
You are probably thinking of $resource which allows you to predefine HTTP request URLs and their parametric components, or $route which also allows similar parametric URL functionality but within the context of your angular front end rather than back end.
Any params passed in the way you pass them will end up as query / GET style parameters.
http://docs.angularjs.org/api/ng.$http
params – {Object.<string|Object>} – Map of strings or objects which will be turned to ?key1=value1&key2=value2 after the url. If the value is not a string, it will be JSONified.