AngularjS : Passing an object to controller using $state.go() - javascript

I am trying to pass an object to a controller via $state.go().
app.js :
.state('class', {
url: '/class/:programId',
views: {
'content#': {
templateUrl: 'class.html',
controller: 'ClassController'
},
data: {
requireLogin: true
}
}
}).state('classLevel', {
url: '/classLevel',
views: {
'content#': {
templateUrl: 'partials/classLevel.html',
controller: 'ClassLevelController',
params: { obj: null }
},
data: {
requireLogin: true
}
}
})
controller :
controllers.controller('ClassController', ['$scope', '$state', '$rootScope', '$stateParams', 'myService',
function($scope, $state, $rootScope, $stateParams) {
var myClass = myService.getList(url here);
myClass.then(function (data) {
// getting data here
});
$scope.loadClassLevel = function(summaryId, sessionId){
var CurrentDate = moment().unix();
var yourObj = {};
yourObj.currentTime = CurrentDate;
yourObj.summaryId = summaryId;
yourObj.sessionId = sessionId;
$state.go('patientFeelingLevel',{obj:yourObj});
}
});
controllers.controller('ClassLevelController', ['$scope', '$state', '$rootScope', '$stateParams',
function($scope, $state, $rootScope, $stateParams) {
console.log("$state :",$state);
});
I am trying to pass object from ClassController to ClassLevelController. But in console.log I am getting
params: Object
obj: null
Help me how to pass that object to next controller (ClassLevelController here).

You should use not $state to access the parameters that you passed, but $stateParams service.
Try this one:
console.log("$stateParams :",$stateParams);
That's because your state object will be always the same as at the start of your app.
Here is some example which shows that $stateParams is changing, but $state isn't.

Related

$stateParams empty ui router

I have a state as such:
.state('home.deletemsg', {
views: {
"contentworker#": {
url: '/delete/:entityname/:id/:redirectstate',
templateUrl: "Scripts/proteanapp/templates/delete.html",
controller: 'deletectrl',
controllerAs: 'del',
authenticate: true
}
}
Then in the controller I have:
return app.controller('deletectrl', ['$scope', '$rootScope', '$stateParams', function ($scope, $rootScope, $stateParams) {
debugger;
// check for ui router error
var del = this;
del.entityname = $stateParams.entityname;
del.entityid = $stateParams.id;
}]);
Calling $state.go from a controller like :
$state.go('home.deletemsg', { 'entityname': cd.Customer.Name, 'id': cd.Customer.CustomerID }, { 'location': false, 'notify': true });
But the $stateParams is empty, I don't understand why it is empty. I have tried putting an params object into the state and also resolve.
$stateParams.entityname //undefined
$stateParams.id //undefined
url option should be present there on state definition directly, not inside views object of state. But even your controller should not have been called the way you have configured your state.
Code
.state('home.deletemsg', {
//url should present here, rather than putting it inside `views`
url: '/delete/:entityname/:id/:redirectstate',
views: {
"contentworker#": {
templateUrl: "Scripts/proteanapp/templates/delete.html",
controller: 'deletectrl',
controllerAs: 'del',
authenticate: true
}
}

$location.path() not working in AngularJS

I have been trying to redirect my application to the following link using
$location.path('/enterprise/update/' + enterprise.id);
The current url when I click the button is http://localhost:8080/#/enterprise/view
and I would like it to be changed to http://localhost:8080/#/enterprise/update/0
(The 0 here represents the id)
The edit function is the one which is called when I click on the button to redirect.
Relevant code:
EnterpriseCtrl.js
app.controller('EnterpriseCtrl', ['$scope', 'Enterprise', '$location','$http','$route','$routeParams','$resource', function($scope, Enterprise, $http, $route, $location, $rootScope) {
$scope.enterprises = Enterprise.list({}, function (response) {
return response;
});
$scope.add = function(){
Enterprise.save($scope.enterprise,function (){});
$scope.enterprise = null;
};
$scope.delete = function(enterprise, index){
alert("Do you really want to delete an Enterprise at index " + (index+1) + "?");
//book.$remove();
Enterprise.remove(enterprise);
$scope.enterprises.splice(index, 1);
};
$scope.edit = function(enterprise){
console.log(enterprise.id);
console.log(location);
console.log($location);
$location.path('/enterprise/update/' + enterprise.id);
};
// $scope.enterprise = Enterprise.get({id: $route.current.params.id});
$scope.update = function(){
Enterprise.update($route.current.params.id);
$location.path($rootScope.history.view);
};
}]);
app.js
var app = angular.module('mpsApp', ['ngRoute','ngResource']);
app.config(['$routeProvider','$locationProvider',
function ($routeProvider,$locationProvider) {
$routeProvider.
when('/', {
templateUrl: 'home.html'
}).
when('/enterprise/view', {
controller: 'EnterpriseCtrl',
templateUrl: 'showEnterprise.html'
}).
when('/enterprise/add', {
controller: 'EnterpriseCtrl',
templateUrl: 'addEnterprise.html'
}).
when('/enterprise/update/:id', {
controller: 'EnterpriseCtrl',
templateUrl: 'updateEnterprise.html'
}).
otherwise({
redirectTo: '/'
});
}
]);
The error that I get is
TypeError: $location.path is not a function
at Scope.$scope.edit (EnterpriseCtrl.js:29)
at $parseFunctionCall (angular.js:12330)
at callback (angular.js:22940)
at Scope.$eval (angular.js:14381)
at Scope.$apply (angular.js:14480)
at HTMLButtonElement.<anonymous> (angular.js:22945)
at HTMLButtonElement.eventHandler (angular.js:3009)
Your dependency injection array/parameters are out of order. Should be:
[ '$scope', 'Enterprise', '$location', '$http', '$route', '$routeParams', '$resource',
function($scope, Enterprise, $location, $http, $route, $routeParams, $resource) {
Note, how each single array element service corresponds to the parameters in the function.

Creating a custom provider angularjs

I am trying to create some routing that will resolve calls to my rest api
before the page loads. Because I can't inject a service created using
app.factory(), I am attempting to create a provider to do this so I can use it in my config routing, but I'm
getting Error: [$injector:unpr] Unknown provider: $http
I want to be able to call the provider in mainFlow.api for 4 or five endpoints
that will resolve before the page loads. Am I going about this the correct way?
My code:
service.js
var mainApp = angular.module('mainApp');
mainApp.provider('choiceService', ['$http', function($http) {
return {
$get: function() {
return {
get: function(url) {
return $http.get(url);
}
};
}
};
}]);
config.js
var mainApp = angular.module('mainApp', [
'ui.router'
]);
mainApp.config(['$stateProvider', '$urlRouterProvider', '$choiceServiceProvider',
function($stateProvider, $urlRouterProvider, choiceServiceProvider) {
$stateProvider
.state('mainFlow', {
abstract: true,
url: '/base',
template: '<ui-view/>'
})
.state('mainFlow.choose-main', {
url: '',
templateUrl: '/choose_main.html',
})
.state('mainFlow.contact', {
controller: 'ContactFormController',
url: '/contact-details',
templateUrl: '/panel_contact_info.html',
})
.state('mainFlow.api', {
url: '/about-your-api',
controller: 'ApiFormController',
templateUrl: '/panel_about_your_api.html',
resolve: {
choice: function(choiceServiceProvider) {
return choiceServiceProvider.get('/api/yes-no-choice/');
},
other_choice: function(choiceServiceProvider){
return choiceServiceProvider.get('/api/my-other-choice/')
}
}
})
Then I can use the resolved data in controller.js
controller.js
var mainApp = angular.module('mainApp');
mainApp.controller('ApiFormController', [
'$scope',
'$state',
'choiceService',
function($scope, $state, choiceService) {
$scope.choices = choiceService;
}
]);
I was passing $http in service.js when there was no need. I was also passing in '$choiceServiceProvider' in config.js when it should have been just 'choiceServiceProvider'

Undefined is not a function error when using factory method in angularJS

I'm having problems finding the solution to TypeError: undefined is not a function in my code.
I have the following app.js:
var app = angular.module('test', ['ngRoute', 'test.services', 'test.directives', 'test.controllers']);
app.config(function ($routeProvider, $httpProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.
when('/q/:q', {
templateUrl: '/templates/productlist.html',
controller: 'ProductCtrl'
}).
otherwise({
redirectTo: '/q'
});
});
Then I have a controller
var controllers = angular.module('test.controllers', []);
controllers.controller('ProductCtrl', ['$scope', '$routeParams', 'ProductFactory',
function ($scope, ProductFactory, $routeParams) {
$scope.query = $routeParams.q;
$scope.products = ProductFactory.query({query: $scope.query});
}]);
And a factory
var services = angular.module('test.services', ['ngResource']);
var baseUrl = 'http://localhost\\:8080';
services.factory('ProductFactory', function ($resource) {
return $resource(baseUrl + '/test/smart/:query', {}, {
query: { method: 'GET', isArray: true }
})
});
This code results on load in the above mentioned TypeError on the line $scope.products = ProductFactory.query({query: $scope.query}); in my controller.
Further, when debugging my code I see that $routeParams.q is null or undefined.
What I want is that in my controller the $scope.products variable becomes an array with the result of the query.
What am I doing wrong?
Please try with correct function arguments,
controllers.controller('ProductCtrl', ['$scope', '$routeParams', 'ProductFactory',
function ($scope /*ProductFactory*/, $routeParams, ProductFactory) {
$scope.query = $routeParams.q;
$scope.products = ProductFactory.query({query: $scope.query});
}]);

AngularJS: Load templateUrl after all data received by the controller

I'd like to display my template when the data coming from my server are loaded.
I created a module called Services with inside some services to load my data, I'm using HomeService for my example.
var app = angular.module('MyApp', ['Services']);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/',
{
templateUrl: 'home.html',
controller: 'Home_Ctrl',
resolve: {
loadData: //??
}
});
}]);
app.controller('Home_Ctrl', ['$scope', 'HomeService', function($scope, HomeService) {
$scope.data = HomeService.getData();
}
I guess I need to create a promise to do that. Is it possible to put this function inside my controller?
I mean, I don't want something like that:
var ctrl = app.controller('Home_Ctrl', ['$scope', 'HomeService', function($scope, HomeService) {
//Do something
}
//Promise
ctrl.fct = function($q) {
}
I want something like that:
app.controller('Home_Ctrl', ['$scope', '$q', 'HomeService', function($scope, $q, HomeService) {
//Do something
//Promise
this.fct = function() {}
}
Any idea?
Thanks.
You could use resolve property of controller.
You could create a object which will return promise and assign to controller resolve function and inject the same in controller definition kindly see very simple example
$routeProvider.when('/ExitPoll', {
templateUrl: '/partials/ExitPoll.html', controller: exitpollController, resolve: {
responseData: ['$http', function ($http) {
return $http.get('/Candidate/GetExitPolls/hissar').then(function (response) {
return response.data;
});
}],
}
});
var exitpollController = ['$scope', '$http','responseData','$rootScope',
function ($scope, $http, responseData, $rootScope) {
}];

Categories