I have perfectly initialized $stateProvider and I'm using all this states with ui-sref. Works great.
User presses the button and thorugh the $stateProvider goes to the edit page.
On this page I have a form which does $http request:
this.pushData = function (data) {
$http.post('/data/' + $stateParams.dataId + '/otherdata', JSON.stringify({
id: otherdata.id,
name: otherdata.name
}), configAuth).then(
function success(response) {
var addedData = response.data;
$.notify({message: addedData.name + " has been added"},{type:'success'});
$state.go('roleInfo({roleId: $stateParams.roleId})');
},
function error(data) {
console.log(data);
$.notify({message: data.data.message},{type:'danger'});
}
);
}
And I want to do redirect to other view if everything is fine. But this:
$state.go('roleInfo({roleId: $stateParams.roleId})');
doesn't work. How can I do $state.go with params?
The way you are trying that would work with ui-sref directive, while calling it using $state.go method, you should pass 1st parameter is stateName & then pass params in Object format.
$state.go('roleInfo', {roleId: $stateParams.roleId});
Try this:
$state.go('myStateName', {roleId: $stateParams.roleId});
You can read the docs here
i have changed
$state.go('roleInfo({roleId: $stateParams.roleId})'); to
$state.go('roleInfo',{roleId :$stateParams.roleId});
this will work
this.pushData = function (data) {
$http.post('/data/' + $stateParams.dataId + '/otherdata', JSON.stringify({
id: otherdata.id,
name: otherdata.name
}), configAuth).then(
function success(response) {
var addedData = response.data;
$.notify({message: addedData.name + " has been added"},{type:'success'});
$state.go('roleInfo',{roleId :$stateParams.roleId}); },
function error(data) {
console.log(data);
$.notify({message: data.data.message},{type:'danger'});
}
);
}
Related
I need to retrieve a value from an async service to add as a parameter to every rest call. The casService.getProxyTicket() is an $http call...
I have the following code :-
myFactories.factory('myFactory', [
'Restangular'
, 'casService'
, function (Restangular
, casService) {
return Restangular.withConfig(function (config) {
config.setBaseUrl('https://host:port/somecontext/rest');
config.addFullRequestInterceptor(function (element
, operation
, route
, url
, headers
, params
, httpConfig) {
... What do I need to do here?
casService.getProxyTicket(url).then(function(st){
console.log('proxyTicket = ' + st.data.ticket);
});
params.ticket = ?????? <= st.data.ticket
...
return {
element: element
, headers: headers
, params: params
, httpConfig: httpConfig
}
});
}).service('myCollection');
}]
);
...thanks in advance!!!!
Ok, my lack of understanding coming from a backend developer's background...
This can/should NOT be done this way! I was trying to make the call to get a proxy ticket synchronous.... DON'T DO IT!
What I did was to rearrange my code thus ...
function readItem(id) {
var endpoint = myFactory.one(id);
return casService.getProxyTicket(endpoint.getRestangularUrl())
.then(function (response) {
return endpoint.get({ticket: response.data.proxyTicket});
}).then(function (response) {
return response.plain();
});
}
...works like a charm!
This seems like a simple problem, and I must be overlooking something small.
I have a function that accesses Spotify API and searches for an artist. I know that accessing this route via a normal URL returns a result. (e.g. http://localhost:3001/search?artist=%27Linkin%20Park%27) Here the code that does that:
router.get('/search', function(req, res, next)
{
var artist = req.param('artist');
console.log("Artist: " + artist);
smartSpot.getArtistID(artist, function(data)
{
console.log("Data: " + data);
res.json(data.id);
});
});
Then, there is the code on the front end to search for the artist. This is all done via angular.
angular.module('smart-spot', [])
.controller('MainCtrl', [
'$scope', '$http',
function($scope, $http)
{
$scope.createPlaylist = function()
{
var artist = $scope.artist;
console.log(artist);
window.open("/login", "Playlist Creation", 'WIDTH=400, HEIGHT=500');
return $http.get('/search?=' + $scope.artist) //this doesn't pass in the artist
.success(function(data)
{
console.log(data);
});
}
}
]);
The $http.get() does not pass in the $scope.artist` value properly.
Looks like you might be missing the "artist" query param in your string concatenation.
$http.get('/search?artist=' + $scope.artist)
Alternatively, you could pass the artist as a query param.
function createPlaylist() {
return $http.get('/search', { params : { artist : $scope.artist } })
.then(function(response) {
return response;
}, function(error) {
return $q.reject(error);
});
}
Also, I would avoid using .success. I believe that's depreciated in favor of the syntax above. First param is success function, second is fail function.
you can pass parameters via
$http.get('/search', {
params: {
artist: $scope.artist
}
})
.success(function(data)
{
console.log(data);
});
I'm attempting to fire off a POST request upon selection of an option within my Angular app. Below is my current code.
HTML:
<select ng-options="option for option in linked.maxOptions" ng-model="linked.selectedMax" ng-change="linked.changeMax()"></select>
Controller:
var playerId = $routeParams.playerId;
vm.changeMax = function() {
playersService.setMaxPoints({
playerId: playerId,
max: vm.selectedMax
}).$promise.then(function(res){
return res.success;
}, function(res) {
alert('Couldn\'t update number of points to ' + vm.selectedMax + ':' + res.success);
});
};
Service:
angular.module('gameApp')
.factory('playersService', ['$resource',
function($resource) {
var base = '/api/players/:playerId/';
return $resource(base, {}, {
setMaxPoints: {method: 'POST', url: base + 'maxPoints/' + ':max'}
});
}]);
The problem is that my parameters are not being passed to my service method for some reason as it attempts to hit this endpoint:
http://localhost:3010/api/players/maxPoints
Where does playerId come from? It's not declared nor passed as a parameter to your changeMax function.
Here is how I declare resources. The syntax is a bit easier than yours so it's less error prone:
angular.module('myApp')
.factory('ActivityData', function($resource) {
return $resource('/service/data/:userEmail/:dataType', {dataType: 'all'},
{
getTotals: {method:'GET', cache: true, params: { dataType: 'total'}}
}
});
The issue was in my controller. I was handling a POST request just like I handle GET requests which apparently does not work. I needed to pass a second, in this case empty, object to my service method call to get things working. I believe this is where you would pass any 'body' of data to your service call:
vm.changeMax = function() {
playersService.setMaxPoints({
playerId: playerId,
max: vm.selectedMax
}, {}).$promise.then(function(res){
return res.success;
}, function(res) {
alert('Couldn\'t update number of points to ' + vm.selectedMax + ':' + res.success);
});
};
I am in edit state i am trying to update riskDto but i am getting an error about some object i dont know what i am doing wrong please help.
Code tried so far...
ctrl.js
RiskService.saveAllignRiskToProcess($scope.riskDTO,$stateParams.processKey).then(function (response) {
if ($scope.editMode) {
$scope.hideYesBtn = true;
$scope.hideNoBtn = true;
$scope.showOkBtn = true;
$scope.messageText = 'Updated Risk Within Process successfully';
$scope.confirmationWin.open().center();
$scope.okCallback = $scope.riskAlignToProcessBack;
}
}
});
facotry.js
saveAllignRiskToProcess: function(processKey) {
return $http.post('app/risk/rest/riskTocontrol/saveCreateAndAlignNewRiskToProcess/' + processKey);
}
state.js
.state('createAndAlignRisk', {
url: '/risk/cnaRsk/:processKey',
templateUrl: 'views/risk/createNewRisk.html',
controller: 'RiskCtrl',
data: {
authenticate: true
}
})
consoleError
/riskTocontrol/saveCreateAndAlignNewRiskToProcess/[object%20Object]
If you want to pass both object $scope.riskDTO , $stateParams.processKey to service then the your service method needs to be change along with caller method code
Code
RiskService.saveAllignRiskToProcess($scope.riskDTO,$stateParams.processKey)
.then(function (response) {
//..code here
});
Service
saveAllignRiskToProcess: function(processKey, riskDTO) {
var url = 'app/risk/rest/riskTocontrol/saveCreateAndAlignNewRiskToProcess/' + processKey
return $http.post(url ,JSON.stringify({ 'serverSideParamName': riskDTO}) );
}
From angularjs doc
post(url, data, [config]);
data - Request content
The Data parameter is necessary that you can see from a documentation. You missed it in:
saveAllignRiskToProcess: function(processKey) {
return $http.post('app/risk/rest/riskTocontrol/saveCreateAndAlignNewRiskToProcess/' + processKey);
}
I am using http.jsonp to make cross domain calls and everything works fine, My config object is as below:
var config = {
params: {
action: "query",
prop: "revisions",
format: "json",
rvlimit: 50,
titles: 'obama',//works
// titles: val, //doesn't works
callback: "JSON_CALLBACK"
}
};
var url = "http://en.wikipedia.org/w/api.php?";
$http.jsonp(url, config).success(function(data) {
var pages = data.query.pages;
for (var pageid in pages)
{
$scope.revisions = pages[pageid].revisions;
break; // expect only one page
}
$scope.loaded = true;
});
when the titles has a static value of obama, it works fine however I added an input box from where I am getting the value and I am trying to set the value of the input box to titles and load the particular feed, however it is not working. I have reproduced the issue on jsfiddle,
Any Ideas how to fix this/
http://jsfiddle.net/L4qZZ/
I assume you need to fetch the contents after the user hits the "Go" button.
The problem with your code is that you are using val to set the title instead of $scope.val.
If you update that and then correct the code to make the HTTP request when user clicks the button, your data is fetched as expected.
Fiddle that demonstrates the solution.
Just type "obama" into the input and click the button to get your data.
since you are not using $scope for getting the ng-model values, use $scope.val instead of val
Try this out
var config = {
params: {
action: "query",
prop: "revisions",
format: "json",
rvlimit: 50,
titles: $scope.val,
callback: "JSON_CALLBACK"
}
};
It's better to reorganize your code a little. Move data loading functionality into a service like this one:
app.factory('Wiki', function ($q, $http) {
return {
loadData: function (title) {
var deferred = $q.defer(),
config = {
params: {
action: "query",
prop: "revisions",
format: "json",
rvlimit: 50,
titles: title,
callback: "JSON_CALLBACK"
}
},
url = "http://en.wikipedia.org/w/api.php?";
$http.jsonp(url, config).success(function(data) {
var pages = data.query.pages;
for (var pageid in pages) {
deferred.resolve(pages[pageid].revisions);
break;
}
});
return deferred.promise;
}
};
});
And then you can use it like this in controller:
app.controller('HistoryController', function($scope, Wiki) {
$scope.loaded = false;
$scope.getData = function(val) {
Wiki.loadData(val).then(function(data) {
$scope.loaded = true;
$scope.revisions = data;
});
}
$scope.getData('obama');
});
Using services makes everything more flexible when you deal with data.
Demo: http://jsfiddle.net/L4qZZ/1/