I trying to call other route in angular, similar this
$location.path($scope.productPath+"/approveProducts/").search({ids});
I want send the list of ids to other controller but the ids are sending by url
http://localhost:8080/#/product?ids=1130&ids=1132&ids=7428&ids=15574&ids=15579&ids=15580&ids=6798968768697789
I need send ids similar a post requisition, not in a url, because i have a many ids in my call
How i do this in angular, send parameters and change my route to other controller?
I believe a better approach might be to utilize the angularjs service/factory to persist your data.
example:
.service('AngularJsService', function() {
var listOfIds = [];
return {
saveData: function(theIdsToSave) {
listOfIds = theIdsToSave;
},
getData: function () {
return listOfIds;
}
}
}
.controller('OriginatingController', function($location, AngularJsService) {
function navigateToTargetController() {
AngularJsService.saveData([1,2,3,4]);
$location.path('pathToTargetController');
}
}
.controller('TargetController', function($location, AngularJsService) {
function retrieveData() {
var ids = AngularJsService.getData();
// ids = [1,2,3,4]
}
}
You can use $http for send your params and then change your route
var req = {
method: 'POST',
url: 'http://example.com',// address for sending ids
headers: {
'Content-Type': undefined
},
data: { test: 'test' }
}
$http(req).then(function(){
// this you can to change your url
$location.path($scope.productPath+"/approveProducts/");
}, function(){...});
Related
I am developing a web application in Angularjs. I am making some API calls using $http service. I am using factories to call $http services. I have below controller.
(function () {
angular.module('RoslpApp').controller('SavedVechilces', ['$scope','DeleteVechicle', function ($scope,DeleteVechicle)
$scope.deletesavedCar = function (sref) {
DeleteVechicle.deleteCar(sref.CarID).success(function (resposne) { console.log(resposne) }.error(function (error) { console.log(error)}))
}
}]);
})();
RoslpApp.factory("DeleteVechicle", ['$http', '$cookieStore','cfg', function ($http, $cookieStore,cfg) {
var factoryObject = {};
var baseurl = cfg.Baseurl;
var LoginID = $cookieStore.get("LoginID");
var cookiePreferredLanguage = $cookieStore.get('PreferredLanguage');
var urlapi = baseurl + "api/Vehicle/DeleteSavedVehicle";
factoryObject.deleteCar = function (carID) {
var request = {
url: urlapi,
method: 'POST',
data: {
LoginID: LoginID,
CarID: carID
},
headers: {
RequestedPlatform: "Web",
RequestedLanguage: cookiePreferredLanguage
},
};
return $http(request);
}
return factoryObject;
}
]);
When I run above code I will get Unknown provider: DeleteVechicleProvider <- DeleteVechicle <- SavedVechilce error. I injected DeleteVechicle in my controller. May I know the way I am CarID to the factory and returning response is the correct way? Any help would be appreciated. Thank you.
There are two issues, you need to change your controller/factory as,
RoslpApp.controller
also the request should be,
DeleteVechicle.deleteCar(sref.CarID).then(function(response){
console.log(resposne)
},function(error){
console.log(error)
});
I need to pass rest=1 in every ajax call. How do i do that. Can i add it at a global level something like Transform Request
This is how my service looks like. I have several such service where only the endpoint or apipath changes
return $resource(apiPath, {
rest: 1,
}, {
query: {
method: 'GET',
isArray: true,
}
}
);
Also It would be good if i could only add to calls if the ajaxurl/apiurl is not in a exclude list
Try adding this in your main app config block.
$httpProvider.interceptors.push(function() {
return {
'request': function(config) {
if (config.method === 'POST')
angular.extend(config.data, {rest: 1});
return config;
}
};
});
I have a json file of events setup like this:
{
2: {
sched_conf_id: "38",
title: "Coffee Break",
},
3: {
sched_conf_id: "39",
title: "registration",
},
}
I setup and angular factory like this:
.factory('eventFactory', ['$resource',
function($resource) {
return {
query: function(event_id) {
return $resource('/assets/events.json', {}, {
query: { method: 'GET', params: {id:event_id}, isArray: false }
}).query();
}
}
}
])
and lastly I have my angular controller which calls the query method from the factory with the id being the id from the url:
.controller('eventCtrl', function($scope, $routeParams, eventFactory) {
var eventId = $routeParams.event_id;
$scope.eventData = eventFactory.query(eventId);
})
The return data seems to be just the entire events.json file rather than just the specific id I want to query for in the parameters. In the params I am trying id but that is obviously not correct. Using this setup how can I return just the data from event_id: 2?
Assuming your production scheme is going to be fetching just a static file that doesn't do anything with arguments passed in, you need to extract the record you need after it's returned from the server.
Basically, you're requesting something like http://yourhost.com/assets/events.json?event_id=3 and if it's just a static file, the server can't do anything with that parameter. In practice, I would think you'd actually be requesting a response from a web service that can handle that, in which case your client-side code would probably work as-is.
In this specific case, however, I would think that you could handle this with an interceptor. Something like this:
.factory('eventFactory', ['$resource',
function($resource) {
return {
query: function(event_id) {
return $resource('/assets/events.json', {}, {
query: { method: 'GET', isArray: false,
interceptor: {response:
function(data){ var d = JSON.parse(data);
return d[event_id];
}
}
}
});
}
}
}
])
I don't have an environment set up to test this at the moment, but I think it should work. I have a couple places in my own code where I do something similar, for other reasons.
I'm using Angular with ngResource and i've got an api url:
GET http://my.com/rest/items?inState=TRANSIENT&inState=FINAL
How could I do query with two (not uniq) params 'inState'?
This is my Resource factory:
.factory('Resource', function ($resource, REST_URL) {
return {
items: $resource(REST_URL + 'rest/items',
{},
{
get: {method: "GET", params: {inState: '#inState'}}
})
};
})
And this is the way I'm call it:
//GET http://my.com/rest/items?inState=TRANSIENT
Resource.items.get({inState: 'TRANSIENT'}, function (data) {
//...
}, function (responce) {
//...
});
This is works but the problem is in how I'm send params - as object: {inState: 'TRANSIENT'}
I cannot write something like
{inState: 'TRANSIENT', inState: 'FINAL'}
beacuse of fields must be uniq
P.S. I know that it may be done with $http.
That's how to do this:
{inState: ['TRANSIENT', 'FINAL']
Example:
//GET http://my.com/rest/items?inState=TRANSIENT&inState=FINAL
Resource.items.getHistory({inState: ['TRANSIENT', 'FINAL']}, function (data) {
//...
}, function (responce) {
//...
});
Not sure if you have control over what is consuming the parameters, but if you do you could try passing the parameters as an object with an array of objects in it, like this:
{ states : [{inState : 'TRANSIENT'}, {inState : 'FINAL'}]}
Then just iterate through the states array and check each inState property.
New to AngularJS and trying to get a grasp of the framework, and trying to build a basic CRUD app. I can't seem to figure out what is needed to Update an existing record. Here is my service:
angular.module('appServices', ['ngResource']).
factory('App', function ($resource) {
var Item = $resource('App/:AppId', {
//Default parameters
AppId: '#id'
}, {
//Actions
query: {
method: 'GET',
isArray: true
},
getById: {
method: 'PUT'
},
update: {
method: 'POST'
}
});
return Item;
});
I can run a basic Get all query, and getById to populate an edit form, but that's where I'm stuck. Here is example code for getById
$scope.apps = App.query();
$scope.getEdit = function(AppId) {
App.getById({id:AppId}, function(app) {
$scope.original = app;
$scope.app = new App(app);
});
};
$scope.save = function() {
//What type of information should go here?
//Do I need to make changes to the appServices?
};
I guess, I'm just not sure what's next concerning Updating existing information, or how the "app" object gets passed to the API, can anyone point me in the right direction, or show me a quick update method?
This is a really messy way of handling save operations in angular. For one - you should not be using PUT operations for retrieval requests and secondly - all of this is already built-in to angular. See below.
var Item = $resource( 'App/Details/:AppId', { AppId: '#id' } );
var item = Item.get({ id: 1 }, function( data ) {
data.setAnothervalue = 'fake value';
data.$save();
);
What I'm doing here is retrieving an "Item" and then immediately saving it with new data once it's returned.
Angular JS provides a stack of defaults already, including query, save, remove/delete, get.etc. And for most RESTful APIs, you really shouldn't need to add much, if anything at all. See the resource docs for more information, particularly the information on defaults: http://docs.angularjs.org/api/ngResource.$resource
Additionally, once you get a handle on that - you may want to use $save for both create/update operations, but using POST/PUT (RESTful conventions). If you do, see my article that I wrote about not too long ago: http://kirkbushell.me/angular-js-using-ng-resource-in-a-more-restful-manner/
After doing a bit more research, and reviewing Daniel's link (thanks). I got it working.
Controller method:
$scope.save = function() {
$scope.app.update();
};
Service Factory:
var Item = $resource('App/Details/:AppId', {
//Default parameters
AppId: '#id'
}, {
//Actions
query: {
method: 'GET',
isArray: true
},
getById: {
method: 'PUT'
},
update: {
method: 'POST'
}
});
Item.prototype.update = function (cb) {
console.log(this.AppId);
return Item.update({ AppId: this.AppId },
angular.extend({}, this, { AppId: undefined }), cb);
};
return Item;