$stateParams won't pass the values - angularjs

I am trying to pass an object by a simple $state.go(), but all I get is default values 0 and ""
angular ui router:
placesApp.config(($stateProvider, $urlRouterProvider) => {
$urlRouterProvider.otherwise("/home");
$stateProvider
.state("home", {
url: "/home",
templateUrl: "views/search-result.html",
controller: "HomeCtrl"
})
.state("placeDetail", {
url: "/place-detail",
templateUrl: "views/place-detail.html",
controller: "PlaceDetailCtrl",
params: {
placeId: 0,
placeImg: ""
}
})
});
The link that triggers the function:
<a ui-sref="placeDetail" class="place-name" ng-bind="place.venue.name" ng-click="goToPlaceDetail()"></a>
Place detail function, I should not that this is not HomeCtrl. It is in a directive related to HomeCtrl:
placesApp.directive("placeGrid", () => {
return {
restrict: "E",
replace: true,
controller: ["$scope", "$state", "$stateParams", ($scope, $state, $stateParams) => {
var imgObj = $scope.place.venue.photos.groups[0].items[0];
var placeId = $scope.place.venue.id;
var placeImg = imgObj.prefix + "1280x600" + imgObj.suffix;
var placeInfo = {placeId: placeId, placeImg: placeImg};
$scope.goToPlaceDetail = () => {
$state.go("placeDetail", {placeInfo: placeInfo});
};
}],
templateUrl: "views/place-grid.html"
}
});
placeDetail controller:
placesApp.controller("PlaceDetailCtrl", ["$scope", "$state", "$stateParams", ($scope, $state, $stateParams) => {
$scope.placeId = $stateParams.placeInfo.placeId;
$scope.placeImg = $stateParams.placeInfo.placeImg;
}]);

Don't create new placeInfo property. just pass the object.
var placeInfo = {placeId: placeId, placeImg: placeImg};
$scope.goToPlaceDetail = () => {
$state.go("placeDetail", placeInfo);
};
And access the property like this
$scope.placeId = $stateParams.placeId;
OR
add a new property to state
.state("placeDetail", {
url: "/place-detail",
templateUrl: "views/place-detail.html",
controller: "PlaceDetailCtrl",
params: {
placeInfo: {
placeId: 0,
placeImg: ""
}
}
})

Sorry Have you tried something like:
In your app.config:
.state("placeDetail", {
url: "/place-detail/:placeId/:placeImg",
templateUrl: "views/place-detail.html",
controller: "PlaceDetailCtrl",
params: {
placeId: 0,
placeImg: ""
}
})
then in your HTML:
<a ui-sref="placeDetail({id:place.venue.id,placeImg:place.venue.name})" class="place-name" ></a>
then in your controller (or where you need to get them from url):
placesApp.controller("PlaceDetailCtrl", ["$scope", "$state", "$stateParams", ($scope, $state, $stateParams) => {
function init(){
$scope.placeId = $stateParams.placeId;
$scope.placeImg = $stateParams.placeImg;
}
init();
}]);

Related

AngularJS: Angular UI Bootstrap, pass data from modal to controller

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"
})
}]);

$stateParams parameter undefined

I have the following routing:
$stateProvider
.state('message', {
parent: 'admin',
url: '/message',
templateUrl: './app/gol88/admin/messaging/page/list.page.html',
controller: 'ListController as listCtrl'
})
.state('replyMessage', {
parent: 'message',
url: '/{ticketId:int}/reply', //this should have {id} as stateParams
onEnter: ['$mdDialog', '$state', function($mdDialog, $state) {
$mdDialog.show({
controller: ReplyController,
controllerAs: 'replyCtrl',
templateUrl: '/app/gol88/admin/messaging/page/dialog/reply.html',
parent: angular.element(document.body),
clickOutsideToClose:true
}).then(function(response) {
}, function() {
$state.go('message');
});
}],
onExit: ['$mdDialog', function($mdDialog) {
$mdDialog.hide();
}]
})
;
When I tried to navigate to replyMessage state for the first time and use the $stateParams.ticketId in my Controller I am getting the value. However, when I transitioned to message state , and try to transition to replyMessage state back again, the $stateParams.ticketId is now undefined. Why is that so?
This is my controller for replyMessage state:
var ReplyForm = require('../model/reply_form.model');
ReplyController.$inject = ['$stateParams', 'TicketApiService'];
function ReplyController($stateParams, TicketApiService) {
var vm = this;
vm.ticket = null;
vm.ReplyForm = ReplyForm;
vm.addComment = addComment;
init();
function init() {
console.log($stateParams.ticketId);
/* TicketApiService.details($stateParams.ticketId)
.then(function(response) {
vm.ticket = response;
})
;*/
}
function addComment() {
TicketApiService.addComment($stateParams.ticketId, vm.ReplyForm.toPayload())
.then(function(response) {s.
vm.ticket.comments.unshift(response);
vm.ReplyForm.reset();
})
;
}
}
module.exports = ReplyController;

How to access a form in a modal from a controller

In my controller.js file I have:
angular.module('App').controller('AppCtrl', AppCtrl);
function AddApp(){
var vm = this;
vm.resetForm = resetForm;
function resetForm(){
vm.myForm.$setPristine();
}
}
...
function openModal(message){
var errorMessage = message;
var modalInstance = $modal.open({
templateUrl: 'url',
controller: 'AppCtrl',
controllerAs: 'App',
resolve: {
errorMessage: function () {
return errorMessage;
}
}
});
}
and in my modal I have
<div ng-controller="AppCtrl as App">
<form name=App.myForm>
...
when I use this format it tells me that
vm.myForm is undefined.
This is the closest thing I've found here, but it still did not work for me
Can I access a form in the controller?
You can pass the form by adding it to the resolve:
var modalInstance = $modal.open({
templateUrl: 'url',
controller: 'AppCtrl',
controllerAs: 'App',
resolve: {
errorMessage: function () {
return errorMessage;
},
myForm: function() {
return vm.myForm;
}
}
});
In your modal controller:
angular.module('app').controller('AppCtrl',
['$scope', 'errorMessage', 'myForm',
function ($scope, errorMessage, myForm) {
console.log(myForm);
}]
);

Get controller value in app.js from controller.js

Can anyone help me to pass the variable
$scope.imageRepoUrl from controller.js to app.js
controller.js
.controller('deallistCtrl', ['$scope','deals', function($scope, deals) {
$scope.title = "test";
$scope.deals = deals.payload;
$scope.imageRepoUrl=$scope.$parent.imageRepoUrl;
$scope.appWebUrl=$scope.$parent.appWebUrl;
}])
app.js
.state('app.deallists', {
url: "/deallists",
views: {
'menuContent': {
templateUrl: "templates/deallists.html",
controller: 'deallistCtrl',
resolve: {
deals: ['$http', function($http){
return $http.get('deal/deals').then(function(response){
return response.data;
})
}]
}
}
},
})

angular UI router | $stateParams not working

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');
};
}
});

Resources