angularJS $stateParams fail to pass a value to a controller - angularjs

I have an state declared like this in my main App:
var app = angular.module("contactManagement",
["'ui.router'])
.config(["$stateProvider", "$urlRouterProvider", "$locationProvider",
function ($stateProvider, $urlRouterProvider, $locationProvider) {
$stateProvider.state('contacts.detail', {
url: "/contacts/:contactId",
templateUrl: 'contacts.detail.html',
controller: contactEditCtrl
}
...
and I am trying to pass the parameter "contactId" from the URL to the Controller in another file called contactEditCtrl.js like this:
.module("contactManagement ")
.controller("ContactEditCtrl", ["contactResource", ContactEditCtrl]);
function ContactEditCtrl(contactResource, $stateParams) {
var vm = this;
var contactId = $stateParams.contactId;
vm.title = '';
vm.message = '';
contactResource.get({ id: **contactId** },
...more stuff...
But the contactId does not reach the controller using the $stateParams as it said the documentation.
All I need is to inject that ContactId in the controller, but I do not get it!
Any idea on what I am missing here?

You forgot "params"
.state('contacts.detail', {
url: "/contacts/:contactId",
params:{contactId: null},
..more code...
})

Related

Passing an object using $state.go in AngularJS

I'm new to AngularJS and I'm developing a small contacts app using AngularJS and Material Design.
I'd like to pass an object (using ng-click) containing several fields to a different state using $state.go.
My HTML looks like this:
<md-list-item class="md-2-line" ng-repeat="c in contacts" >
<img src="../img/user.svg" class="md-avatar"/>
<div class="md-list-item-text" ng-click="goToContactInfo(c)" >
My JS code:
app.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
// configure "contacts" page
.state('contacts', {
url: "/contacts",
templateUrl: "contacts.html",
controller: function ($scope, $state) {
$scope.contacts = [
{ name: "aaa", phone: "555555" },
{ name : "bbb" , phone: "666666"}
];
$scope.goToContactInfo = function (contact) {
$state.go("contactInfo", contact);
};
}
})
// configure "contactInfo" page
.state('contactInfo', {
url: "/contactInfo",
templateUrl: "contactInfo.html",
controller: function ($scope, $stateParams) {
var contactInfo = $stateParams.contact;
$scope.name = contactInfo.name;
$scope.phone = contactInfo.phone;
}
})
I expect var contactInfo to be an object containing name and phone but I'm getting an undefined instead.
Your controller should be,
controller: function ($scope, $state) {
var contactInfo = $state.params.contact;
}
EDIT
First of all you cannot pass an Object to another state like this, and there are few mistkaes in your configuration.
You need to define your router config with the parameter. Also consider using an id to pass to another state and retrieve the details using an API call or use localstorage.
Here is the fix, i have considered phone number as the state param here,
.state('contactInfo', {
url: "contactInfo/:phone",
templateUrl: "contactInfo.html",
controller: function ($scope, $state, $stateParams) {
console.log('state2 params:', $stateParams);
var contactInfo = $stateParams.phone;
console.log(contactInfo);
alert(JSON.stringify(contactInfo));
$scope.name = contactInfo.name;
$scope.phone = contactInfo.phone;
}
})
and you need to pass the info as,
$state.go("contactInfo", { phone : contact.phone });
PLUNKER DEMO
$scope.goToContactInfo = function (contact) {
$state.go("contactInfo", {contact}); <-- this
};
.state('contactInfo', {
url: "/contactInfo",
templateUrl: "contactInfo.html",
params:{ <-- this
contact: null
},
controller: function ($scope, $state) {
var contactInfo = $state.params.contact;
alert(contactInfo);
$scope.name = contactInfo.name;
$scope.phone = contactInfo.phone;
}
})

How to get parameter from angular with $routeParams

I want to get some posts by category id. So I need to get a parameter from URL in angular but somehow it seems the route does not call the right controller when I put :id as the parameter in the category route. Here is the controller looks like.
.config(['$routeProvider',function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: "home.html",
controller: "mainController"
})
.when('/category/:id', {
templateUrl: "category.html",
controller: "categoryController",
});
}])
And this is the controller.
.controller('categoryController',['$scope','$http','$ionicModal','$routeParams','$location', function ($scope, $http, $ionicModal,$routeParams,$location) {
var id = $routeParams.id;
var httpUrl = 'http://localhost/myapp/';
var url = httpUrl + 'webservices/get_posts_by_category?cat_id=' + id;
$http.get(url).then(function (result) {
console.log(result);
$scope.posts = result.data;
})
But it shows nothing, event it doesn't fire the console.log(result). Looks like it routes to the wrong controller. I just don't know why. What did I miss?

$http request in angular config - Is it possible?

I am trying to make an $http call inside my publicApp.config in order to retrieve an array of available routes to match with the $urlMatcherFactoryProvider.
Right now, I am hard-coding them to be pageUrls = ['about','contact','another-page'];
But I have an url in my express API which returns an array of available URLS. The api URL is "/page-urls"
Would it be possible to make an $http.get('/page-urls') request inside the config? I know $http is available inside run(), but I need the list of available URLs BEFORE routing via the $stateProvider.
(function() {
'use strict'
var pageUrls = [];
var publicApp = angular.module('publicApp', ['ui.router'])
publicApp.config(['$stateProvider', '$urlRouterProvider', '$urlMatcherFactoryProvider', function($stateProvider, $urlRouterProvider, $urlMatcherFactoryProvider) {
pageUrls = ['about','contact','another-page'];
var urls = pageUrls.join('|');
var urlMatcher = $urlMatcherFactoryProvider.compile("/{source:(?:" + urls + ")}");
$stateProvider
.state('/', {
url: '/',
templateUrl: "views/home/home.view.html",
controller: "homeCtrl"
})
.state('urls', {
url: urlMatcher,
templateUrl: "views/pages/page.view.html",
controller: "pageCtrl"
});
$urlRouterProvider.otherwise('/');
}]);
})();
Create a provider which gets $stateProvider as an injectable. The provider will create a service that does the http request then registers the routes. Inject the service in a run block and initiate route registration.
Something like this:
var publicApp = angular.module('publicApp', ['ui.router'])
publicApp.provider('routes', function($stateProvider, $urlRouterProvider, $urlMatcherFactoryProvider){
function registerRoutes(listOfUrls){
// register routes with $stateProvider
// angular.forEach(listOfUrls, function(url){
// $stateProvider.state...
// });
}
this.$get = function($http){
return {
initialize: function(){
return $http.get('/page-urls').then(function(response){
registerRoutes(response.data);
});
}
};
};
});
publicApp.run(function(routes){
routes.initialize();
});

Pass parameter from Angularjs controller to $stateProvider

This is my Angularjs .config file that opens lead.html page whenever 'tasks' is activated from another html using ui-router.
App
.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider){
$stateProvider
.state('tasks', {
templateUrl: {{name}}.html,
controller:"TasksController"
});
}]);
This is my Taskscontroller.js
App
.controller(
"TasksController", [function($scope, $http,$window) {
var self = this;
self.name = 'lead'; // I wanna use this parameter in templateUrl
console.log("In tasks Controller");
}]);
I want to make the templateUrl take parameter from TasksController so that it redirects to relevant page based on the parameter set in TasksController.
Please guide me how to do this.
Thanks
You could try using $stateParams:
App.config(['$stateProvider', '$urlRouterProvider', '$stateParams', function($stateProvider, $urlRouterProvider, $stateParams) {
$stateProvider
.state('tasks', {
params: {
page: null
},
templateUrl: {{$stateParams.page}}.html,
controller: "TasksController"
});
}]);
Then in your controller:
App.controller("TasksController", [function($scope, $http, $window, $stateParams, $state) {
var self = this;
self.$stateParams.page = 'some_url.html';
self.$state.go('tasks');
}]);
Don't forget the injection in the controller too. Haven't tested this but you may need the $state go like this:
self.$state.go('tasks', { page: 'some_url.html' }, { });

UI router Unknown provider for injecting service into child state resolve

Got Unknown provider when injecting service into the child state resolve function. But if defined a resolve in the parent state, it just works. Below there are some sample codes:
I defined a service module
angular.module('services', [])
.factory('myService', function() {
// my service here
})
and initialize the app
var app = angular.module('app', ['services', 'ui.router']);
app.config(['$stateProvider', '$urlRouterProvider', function($stateProvider,
$urlRouterProvider) {
$stateProvider.state('wizard', {
url: '/wizard',
abstract: true
})
.state('wizard.step1', {
url: '/step1',
templateUrl: ... ,
resolve: {
name: function(myService) {
// do something with mySerice
}
},
controller: function(name) {
// controller codes here
}
})
}]);
I got the error Unknown provider complaining about myService in the wizard.step1 resolve. But if I add a random resolve in the parent state, like
$stateProvider.state('wizard', {
url: '/wizard',
abstract: true,
resolve: {
a: function() { return 1; }
}
})
then it works without error. Wonder what happens here?
In your controller you have to inject your service MyService, so define something like this
.state('wizard.step1', {
url: '/step1',
templateUrl: ... ,
resolve: {
name: ['myService', function(myService) {
// do something with mySerice
}]
},
controller: ['name', function(name) {
// controller codes here
}]
})
You have to inject your service in your config function :
var app = angular.module('app', ['services', 'ui.router']);
app.config(['$stateProvider', '$urlRouterProvider', 'myService',
function($stateProvider, $urlRouterProvider, myService) {
...
Another way is to embed your resolve code in a service and assign directly the service :
app.config(['$stateProvider', '$urlRouterProvider' ,'mySuperService',function($stateProvider,
$urlRouterProvider, mySuperService) {
...
resolve: {
name: mySuperService()
}
.constant('mySuperService', function() {
var serv= function(){
// your code
}
return serv;
}

Resources