My restful controller is receiving a null Request Body from an angular POST and I'm not sure why.
Here's the code for my controller:
adminController.controller('ModalCtrl', ['$scope', '$modal', '$log', 'Profile', 'AvailableProfiles',
function ($scope, $modal, $log, Profile, AvailableProfiles) {
$scope.open = function (uuid, profile) {
var modalInstance = $modal.open({
animation: true,
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
resolve: {
profile: function () {
return profile;
},
AvailableProfiles: function () {
return AvailableProfiles;
}
}
});
modalInstance.result.then(function () {
Profile.save({uuid: uuid}, {profile: profile});
}, function () {});
};
}]);
And here's the code for my service:
adminService.factory('Profile', ['$resource',
function($resource, uuid, profile) {
return $resource(baseUrl + 'candidate/:uuid/profile', {profile}, {
save: {method: 'POST', params: {uuid: uuid}},
});
}
]);
Any thoughts on why this profile object isn't being passed into the post?
Call save on the profile object.
modalInstance.result.then(function () {
profile.$save({uuid: uuid});
}, function () {});
Related
I have correctly setup my angular modal, now I want to pass my modal data back to my controller. I am using the below code.
First my controller calls my factory service that creates the modal popup:
$scope.mymodal = myService.openModal(data);
My service is as:
function openModal (data) {
var uData = null;
if (data) {
uData = {
userName : data.setName,
gender : data.gender
}
}
var modalInstance = $modal.open({
templateUrl: 'modal.html',
controller: 'ModalController',
backdrop: 'static',
keyboard: false,
resolve: {
data: function () {
return uData;
}
}
});
modalInstance.result.then(function () {
return;
}, function () {
});
return modalInstance;
}
See my jsfiddle here for this: http://jsfiddle.net/aman1981/z20yvbfx/17/
I want to pass name & gender that i select on my modal back to my controller, which then populates my page. Let me know what is missing here.
I updated AboutController, ModalController and myService with comments.
Main idea is return data from ModalController with close method. Fiddle
var app = angular.module('myApp', ['ui.router','ui.bootstrap']);
app.controller('IndexController', function($scope, $log) {
});
app.controller("AboutController", ['$location', '$state', '$scope', '$filter','myService', function($location, $state, $scope, $filter, myService) {
var data = "";
$scope.mymodal = myService.openModal(data);
// after modal is close, then this promise is resolve
$scope.mymodal.then(function(resp){
console.log(resp);
})
}]);
app.controller("ModalController", function($location, $state, $scope, $filter, $modalInstance) {
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
$state.go('index');
};
$scope.done = function () {
// return data on close modal instance
$modalInstance.close({genger:$scope.gender,userName:$scope.userName});
};
});
app.factory('ApiFactory', function ($http) {
var factory = {};
return factory;
});
app.factory("myService",[ "$state", "$modal", "ApiFactory",
function ($state, $modal, factory) {
var service = {
openModal: openModal
};
function openModal (data) {
var uData = null;
if (data) {
uData = {
userName : data.setName,
gender : data.gender
}
}
var modalInstance = $modal.open({
templateUrl: 'modal.html',
controller: 'ModalController',
backdrop: 'static',
keyboard: false,
resolve: {
data: function () {
return uData;
}
}
});
// on close, return resp from modal
modalInstance.result.then(function (resp) {
return resp;
}, function () {
});
// return modal instance promise
return modalInstance.result;
}
return service;
}
]);
app.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/index');
$stateProvider
.state('index', {
url: '^/index',
templateUrl: 'index.html',
controller: "IndexController"
})
.state('about', {
url: '^/about',
templateUrl: 'about.html',
controller: "AboutController"
})
}]);
I am trying to follow this example to show a bootstrap modal on a certain state. It works fine without a modal (so the state config should be ok). All needed dependencies (ie angular bootstrap) should be available.
when I do a console.debug($stateParams) before $modal.open I get the correct data, within the $modal.open-method however the stateParams from the last state are returned (the state I am coming from)
Any hints?
EDIT
the relevant state cfg:
.state('publications.view', {
parent: 'publications.productSelection',
url: '/{productSlug:[a-zA-Z0-9-]+}/{docID:[0-9]+}_{slug:[a-zA-Z0-9-]+}',
onEnter: ['restFactory', '$state', '$stateParams', '$modal',
function(restFactory, $state, $stateParams, $modal) {
console.debug($stateParams.docID);
$modal.open({
templateUrl: 'partials/publication.html',
resolve: {
publication: ['restFactory', '$stateParams',
function(restFactory, $stateParams) {
console.debug($state.params);
console.debug($stateParams);
return restFactory.view($stateParams.language, $stateParams.productSlug, $stateParams.docID);
}
]
},
controller: ['$scope', '$sce', 'publication', '$rootScope',
function($scope, $sce, publication, $rootScope) {
$rootScope.pageTitle = publication.data.data.publication.Publication.title;
$scope.publication = $sce.trustAsHtml(publication.data.data.publication.Publication.content);
}
]
});
}
]
});
You can get around this issue by injecting the current $stateParams into the onEnter function, save them as state in some service, and inject that service instead into your modal resolves.
I am adapting the code from here: Using ui-router with Bootstrap-ui modal
.provider('modalState', function($stateProvider) {
var modalState = {
stateParams: {},
};
this.$get = function() {
return modalState;
};
this.state = function(stateName, options) {
var modalInstance;
$stateProvider.state(stateName, {
url: options.url,
onEnter: function($modal, $state, $stateParams) {
modalState.stateParams = $stateParams;
modalInstance = $modal.open(options);
modalInstance.result['finally'](function() {
modalInstance = null;
if ($state.$current.name === stateName) {
$state.go('^');
}
});
},
onExit: function() {
if (modalInstance) {
modalInstance.close();
}
}
});
};
})
Then in your app config section
.config(function($stateProvider, $urlRouterProvider, modalStateProvider) {
modalStateProvider.state('parent.child', {
url: '/{id:[0-9]+}',
templateUrl: 'views/child.html',
controller: 'ChildCtrl',
resolve: {
role: function(Resource, modalState) {
return Resource.get({id: modalState.stateParams.id}).$promise.then(function(data) {
return data;
});
}
}
});
}
I am trying to populate my model from backend(with label and messages) before my contoller get loads. My method is working fine it connects with backend and gets the data but when I am viewing that variable in controller it is coming as undefined. My variable is "Model"
This is my route file
mainApp
.config(["$routeProvider", function ($routeProvider) {
.when(AngularRoutesFactory.AIMSAdmin.SearchBookings, {
templateUrl: aimsAdminViewBase + "Bookings/SearchBookings.html",
controller: "SearchPerioperativeBookingController",
resolve: {
"Model": function (BookingFactory) {
return BookingFactory.GetSearchModel();
}
},
requireAIMSAuthorizeUser: true
})
.otherwise({
redirectTo: AngularRoutesFactory.MainApp.BaseUrl
});
}]);
My Factory is
mainApp.factory("BookingFactory", ["$location", "MainFactory",
function ($location, MainFactory) {
bookingsFactory.GetSearchModel = function () {
bookingsFactory.MainFactory.QueryAPI(apiEndpoint + "GetSearchModel", "GET", function (response) {
bookingsFactory.SearchBookingCriteria = response;
return bookingsFactory.SearchBookingCriteria;
}, null, null, bookingsFactory.LangInfo.Message_GettingBookingModel);
}
return bookingsFactory;
}]);
And this is my controller
mainApp.controller("SearchBookingController", ["$scope", "BookingFactory", "$rootScope", "$location"
, function ($scope, BookingFactory, $rootScope, $location, Model) {
$scope.bbb = Model;
}]);
Edit:
Try handling it this way:
mainApp.config(["$routeProvider", "$q", function ($routeProvider, $q) {
.when(AngularRoutesFactory.AIMSAdmin.SearchBookings, {
templateUrl: aimsAdminViewBase + "Bookings/SearchBookings.html",
controller: "SearchPerioperativeBookingController",
resolve: {
Model: function (BookingFactory, $q) {
var deferred = $q.defer();
BookingFactory.GetSearchModel().then(
function (data) {
deferred.resolve(data);
}, function () {
deferred.reject();
}
);
return deferred.promise;
}
},
requireAIMSAuthorizeUser: true
})
.otherwise({
redirectTo: AngularRoutesFactory.MainApp.BaseUrl
});
}]);
Took guidance from #Fedaykin and came up with following working solution. Please let me know if it is wrong
I just changed my factory method and resolve function by applying $q.defer method and got it working
Changed my factory GetSearchModel method with following code
bookingsFactory.GetSearchModel = function () {
bookingsFactory.MainFactory.QueryAPI(apiEndpoint + "GetSearchModel", "GET", function (response) {
deferred.resolve(response);
}, null, null, bookingsFactory.LangInfo.Message_GettingBookingModel);
return deferred.promise;
}
What I did in route file
var bookingModel= function ($q, BookingFactory) {
var deferred = $q.defer();
BookingFactory.GetSearchModel().then(
function (data) {
deferred.resolve(data);
}, function () {
deferred.reject();
}
);
return deferred.promise;
};
bookingModel.$inject = ["$q", "BookingFactory"];
Then in resolve all I did
.when(AngularRoutesFactory.AIMSAdmin.SearchBookings, {
templateUrl: aimsAdminViewBase + "Bookings/SearchBookings.html",
controller: "SearchBookingController",
resolve: {
"Model": bookingModel
},
requireAIMSAuthorizeUser: true
})
And in controller voila I got the value
mainApp.controller("SearchBookingController", ["$scope", "InitializeMainFactory", "$rootScope", "$location", "Model"
, function ($scope, InitializeMainFactory, $rootScope, $location, Model) {
$scope.Model = Model;
}]);
I'm trying to load a job by Id from the API and pass it to the controller.
.when('/jobs/edit/:id', {
templateUrl: 'partials/jobs/edit',
controller: 'JobCtrl',
resolve: function($routeParams, Job){
var jobId = $routeParams.id;
return {
job: function(){
return Job.get({ id: jobId});
}
};
}
})
Controller:
angular.module('App')
.controller('JobCtrl', function ($scope, Job, $location, $routeParams) {
$scope.newJob = data.job; //does not work
$scope.errors = {};
$scope.save = function (form) {
//...
};
});
Model:
angular.module('App')
.factory('Job', function ($resource) {
return $resource('/api/jobs/:id', {
id: '#id'
}, { //parameters default
update: {
method: 'PUT'
}
});
});
How do I get the data in the controller? My resolve block in the route is not even being executed.
Edit: this page has lots of examples of different types of resolving:
http://phillippuleo.com/articles/angularjs-timing-multiple-resource-resolves-ngroute-and-ui-router
It seems like you resolve implementation is incorrect.
You could try to change router like:
.when('/jobs/edit/:id', {
templateUrl: 'partials/jobs/edit',
controller: 'JobCtrl',
resolve: {
job: function (Job, $routeParams) {
return Job.get({id: $routeParams.id});
}
}
})
And get resoled data in controller by including Job into dependencies:
angular.module('App')
.controller('JobCtrl', function ($scope, job, $location, $routeParams) {
// job is resolved here
$scope.job = job;
$scope.newJob = {};
$scope.errors = {};
$scope.save = function (form) {
//...
};
});
UPDATED
If you want to use JobCtrl either for creating and editing, you can return null in resoled job for new-job-page. It means: There aren't any job yet, till you create one.
.when('/jobs/new', {
templateUrl: 'partials/jobs/new',
controller: 'JobCtrl',
resolve: {
job: function () {
return null;
}
}
})
seems like $stateParams is not working.
passing date like this:
$state.go('state2', { someParam : 'broken magic' });
params being ignored on the target state
console.log('state2 params:', $stateParams); // return empty object {}
code:
var app = angular.module('app', [
'ui.router'
]);
app.config(function($stateProvider) {
$stateProvider
.state('state1', {
url: '',
templateUrl: 'state-1.html',
controller : function ($scope, $state, $stateParams) {
$scope.go = function () {
$state.go('state2', { someParam : 'broken magic' });
};
console.log('state1 params:', $stateParams);
}
})
.state('state2', {
url: 'state2',
templateUrl: 'state-2.html',
controller : function ($scope, $state, $stateParams) {
$scope.go = function () {
$state.go('state1', { someOtherParam : 'lazy lizard' });
};
console.log('state2 params:', $stateParams);
}
});
});
Live example can be found here
thank you.
You can't pass arbitrary parameters between states, you need to have them defined as part of your $stateProvider definition. E.g.
$stateProvider
.state('contacts.detail', {
url: "/contacts/:contactId",
templateUrl: 'contacts.detail.html',
controller: function ($stateParams) {
console.log($stateParams);
}
}) ...
The above will output an object with the contactId property defined. If you go to /contacts/42, your $stateParams will be {contactId: 42}.
See the documentation for UI-Router URL Routing for more information.
if you don't want to define your parameter in the url, you must include a params property on the state you are transitioning to. Otherwise the data will be removed from the $stateParams object. The format of the params object is an array of strings in older versions of angular-ui-router; in newer versions it is an object of empty objects:
params: { id: {}, blue: {}}
See this example:
$stateProvider.state('state1', {
url: '',
params: {
id: 0,
blue: ''
},
templateUrl: 'state-1.html',
controller: function($scope, $state, $stateParams) {
$scope.go = function() {
$state.go('state2', {
id: 5,
blue: '#0000FF'
});
};
console.log('state params:', $stateParams);
}
});
Related question:
Parameters for states without URLs in ui-router for AngularJS
Just passing parameters to a state is not enough. You have to define the parameter explicitly by name in the url property of your state.
If you don't do this, ui-router won't know this state is expecting a parameter and the $stateParams object will not be populated like you want.
Here is an example of how you might modify your state to expect a parameter, inject $stateParams, and do something with said parameter:
$stateProvider.state('state1', {
url: '',
templateUrl: 'state-1.html',
controller : function ($scope, $state, $stateParams) {
$scope.params = $stateParams;
$scope.go = function () {
$state.go('state2', { id : 'broken magic' });
};
console.log('state1 params:', $stateParams);
}
})
.state('state2', {
url: 'state2/:id',
templateUrl: 'state-2.html',
controller : function ($scope, $state, $stateParams) {
$scope.params = $stateParams;
$scope.go = function () {
$state.go('state1', { someOtherParam : 'lazy lizard' });
};
console.log('state2 params:', $stateParams);
}
})
Here is a working example of passing state params on jsfiddle.
the solutions above works but for my case I needed to pass query parameter so I dit it like this:
$stateProvider
.state('state1', {
url: '/state1?other',
templateUrl: 'state-1.html',
controller : function ($scope, $state, $stateParams) {
$scope.params = $stateParams;
$scope.go = function () {
$state.go('state2', { someParam : 'broken magic' });
};
console.log('state1 params:', $stateParams);
}
})
.state('state2', {
url: '/state2?someParam',
templateUrl: 'state-2.html',
controller : function ($scope, $state, $stateParams) {
$scope.params = $stateParams;
$scope.go = function () {
$state.go('state1', { other : 'lazy lizard' });
};
console.log('state2 params:', $stateParams);
}
});
Make a transport and use it!
angular_app.factory('$$transport', function($q) {
var transport;
return transport = {
dfr: $q.defer(),
push: function(v) {
return transport.dfr.resolve(v);
},
then: function(s, f) {
if (f == null) {
f = function() {};
}
return transport.dfr.promise.then(function(_s) {
s(_s);
transport.dfr = $q.defer();
return transport.then(s, f);
}, function(_f) {
f(_f);
transport.dfr = $q.defer();
return transport.then(s, f);
});
}
};
});
$stateProvider.state('state1', {
url: '/state1?other',
templateUrl: 'state-1.html',
controller : function ($scope, $state, $$transport) {
$$transport.then(function(s) {
$scope.param = s
console.log('state1 params:', s);
});
$scope.go = function () {
$state.go('state2', { someParam : 'broken magic' });
}
}
})
.state('state2', {
url: '/state2?someParam',
templateUrl: 'state-2.html',
controller : function ($scope, $state, $$transport) {
$scope.go = function () {
$$transport.push({other:'lazy lizard'});
$state.go('state1');
};
}
});