$stateParams become 'undefined' after passing to the controller - javascript

I set the $stateParam by getting a cell value from a table:
$scope.tableClick = function() {
var tr = $('#Table_1').find('tr');
var id = $(event.target).parent().find("td:first").text();
$stateParams.engineId == id;
$state.go('engineselection');
}
When I stop the debug at this point. It gives me the engineId value.
This is the router part that I use:
$stateProvider.state('engineselection', {
url : '/engineselection:engineId',
templateUrl : 'assets/views/engineselection.html',
controller : 'EngineSelectionCtrl'
})
This is what happens in the controller:
controllers.controller("EngineSelectionCtrl",
["$scope", "$rootScope", "directiveBinder", '$timeout', '$stateParams', '$resource', '$location', 'rtmService', '$state',
function($scope, $rootScope, directiveBinder, $timeout, $stateParams, $resource, $location, myService, $state) {
myService.loadViewWithEngine(function(id, data) {
$scope.views = data;
$scope.$apply();
$('#loadingViews').spin(false);
});
When I stop here before the function and type console $stateParams, it tells me that I have a state parameter named 'engineId' but it is undefined. What should I do to pass the parameter to the controller with its value?

Worked after I have changed $state.go call like this:
$state.go('viewselection', {engineProgramId: id});

Related

AngularJS TypeError is not a function

I have the following code in my service:
testApp.service('detailsService',['databaseService', 'loggedService', '$http', function(databaseService, loggedService, $http){
var details;
this.getDetails = function(name){
return $http({
method : "GET",
url : name
}).then(function(response) {
details= response.data;
console.log(response.data);
return response.data;
});
};
}]);
What i want to do is call this function in my controller when the page(view) is loaded.
testApp.controller('testController', ['$scope', '$location', 'databaseService','detailsService', '$routeParams', function($scope, $location, databaseService, $routeParams, detailsService){
$scope.details;
var selectedDetails = function(name){
detailsService.getDetails(name).then(function(data){
$scope.details= data;
});
};
selectedDetails(name);
}]);
I keep getting the error detailsService.getDetails is not a function.
I'm using the same function from the detailsService in another controller without any problems.
Does anybody know why i keep getting this error?
The error is expected as you are not injecting dependencies properly, You need to use the correct sequence.
testApp.controller('testController', ['$scope',
'$location',
'databaseService',
'detailsService',
'$routeParams',
function($scope, $location, databaseService, detailsService, $routeParams ){
instead of
testApp.controller('testController', ['$scope',
'$location',
'databaseService',
'detailsService',
'$routeParams',
function($scope, $location, databaseService, $routeParams, detailsService){
Note Both the string part and the function arguments need to match up 1:1.
remove the promise in the service.Just return the request. since you are catching the promise from the controller no need to use it in the service
testApp.service('detailsService', ['databaseService', 'loggedService', '$http', function(databaseService, loggedService, $http) {
var details;
this.getDetails = function(name) {
return $http({
method: "GET",
url: name
})
};
}]);
Also make sure the sequence is correct order when you are injecting services.
change this
testApp.controller('testController', ['$scope', '$location', 'databaseService', 'detailsService', '$routeParams', function($scope, $location, databaseService, $routeParams, detailsService )
to this
testApp.controller('testController', ['$scope', '$location', 'databaseService', 'detailsService', '$routeParams', function($scope, $location, databaseService, detailsService , $routeParams)
controller
testApp.controller('testController', ['$scope', '$location', 'databaseService', 'detailsService', '$routeParams', function($scope, $location, databaseService, detailsService , $routeParams) {
$scope.details;
var selectedDetails = function(name) {
detailsService.getDetails(name).then(function(data) {
$scope.details = data;
});
};
selectedDetails(name);
}]);
I got this error because I had added a callback method to a component, but the callback was not used by all the pages where that component was used:
<component [myCallbackFn]="fnNameToBindToFn">
component.ts:
public onClick() {
// some code
this.myCallbackFn();
}
Each time it was not used I got this error which was effectively a NullPointerException (from Java). So in the other uses of <component> in my website I had to add a check in the component before the callback to say:
if (undefined !== this.myCallbackFn) this.myCallbackFn();

Unable to call function as $rootScope is undefined

I am trying to call the function inside the controller 'Notification' when getNotification is called in the SelectNotificationCtlr. However when running this I get an Error stating that $rootScope is undefined on the line below console.log("log");. I have tried passing the $rootScope as a parameter in my getNotification function but still receive the same error.
Please see my code below, any advice or help would be really appreciated.
app.js
selectNotification.controller('selectNotificationCtlr', ['$scope', '$rootScope', 'notificationsService',
function($scope, $http, notificationsService, notificationService, $rootScope) {
$scope.getNotification = function() {
var id = $scope.selectedNotification;
notificationData = notificationsService.getNotifications();
console.log(notificationData);
console.log("log");
$rootScope.$emit("call", {});
}
}
]);
selectNotification.controller('Notification', ['$scope', '$rootScope',
function($scope, $rootScope) {
$rootScope.$on("call", function() {
$scope.parent(notificationService);
});
$scope.parent = function() {
console.log("log");
}
}
]);
Kind regards
CB
Your controller should have dependencies in the right order,
selectNotification.controller('selectNotificationCtlr', ['$scope', '$rootScope', 'notificationsService',
function($scope, $rootScope, notificationsService) {

How to redirect after login

I am trying to redirect a user to different page after user is authenticated. I am using jwt authentication and I tried with $location, $window for redirection but its throwing error $state.go is not a function. I am new to angular and I am guessing there should be way to redirect may using a service in angular but I am still new to factories and service.
I have my state provider like this in state.js file:
myApp.config(function ($stateProvider, $urlRouterProvider) {
// default route
$urlRouterProvider.otherwise("/Home");
var header = {
templateUrl: 'commonViews/Header.html',
controller: function ($scope) {
}
};
var footer = {
templateUrl: 'commonViews/Footer.html',
controller: function ($scope) {
}
};
// ui router states
$stateProvider
.state('Home', {
url: "/Home",
views: {
header: header,
content: {
templateUrl: 'views/HomePage.html',
controller: function ($scope) {
}
},
footer: footer
}
})
.state('LoggedIn', {
url: "/LoggedIn",
views: {
'header': header,
'content': {
templateUrl: 'views/LoggedIn.html',
controller: function () {
}
},
'footer': footer
}
});
});
and loginController.js:
myApp.controller('loginController', ['$scope', '$http', 'jwtHelper', '$localStorage', '$state', function ($scope, $http, jwtHelper, $localStorage, $sessionStorage, $state)
{
$scope.email = "";
$scope.password = "";
$scope.token = "";
$scope.loginForm = function () {
var data = {email: $scope.email, password: $scope.password};
var url = 'rs/loginResource/login';
$http.post(url, data).then(function (response)
{
$localStorage.token = response.data.token;
console.log("Encoded Token in localstorage is:" + $localStorage.token);
if ($localStorage.token) {
// $location.url("/LoggedIn");
$state.go('/LoggedIn');
}
}, function (error)
{
console.log("error", error);
});
};
}]);
further I have to perform refresh token based on expiration time etc, so is it better to have separate the functions like using a service to do the signup and signin?
The problem is the definition of your controller and the way you're handling your injections. And no, referring to your own answer to your question, the problem is not the "order" of the injections. It's a bit worse.
myApp.controller('loginController', ['$scope', '$http', 'jwtHelper', '$localStorage', '$state', function ($scope, $http, jwtHelper, $localStorage, $sessionStorage, $state)
in this code you're mapping '$scope' to a $scope variable, '$http' to $http, 'jwtHelper' to jwtHelper, '$localStorage' to $localStorage and '$state' to $sessionStorage, and you're not mapping anything to $state. So obviously you get an error when you try to call a method on an undefined $state variable.
So in short, you're injecting 5 dependencies and you're assigning 6 variables to your dependencies, which in turn results in things not doing what they're supposed to do.
You can use Angular $window:
$window.location.href = '/index.html';
$state. go accepts the view name, not the URL. Replace '/LoggedIn' with Logged and you should be good.
Use $state.go instead of $window and location.
Add $state injector on controller
write code $state.go('LoggedIn');
Instead $state.go('/LoggedIn');
Write state name('LoggedIn') instead of url('/LoggedIn').
Hopefully this will work in your case.
You need to add $window as a dependency to your controller if you are using $window,
myApp.controller('loginController', ['$scope', '$http', 'jwtHelper', '$localStorage', '$state','$window', function ($scope, $http, jwtHelper, $localStorage, $sessionStorage, $state,$window)
{
$window.location.href = '/index.html';
}
otherwise change the route like this, here also you need to inject $state,
myApp.controller('loginController', ['$scope', '$http', 'jwtHelper', '$localStorage', '$state','$window','$state', function ($scope, $http, jwtHelper, $localStorage, $sessionStorage, $state,$window,$state)
{
$state.go('LoggedIn');
}

Updating value on view angular

I have a form in angular, that submits to an API, that returns a 201 status code, and the id and token of the object that was created. My idea is to open up a modal, with that token and show it to the user.
The value of $scope.object.token is updated, but I can't update that state in the view. I tried, $scope.$apply() I get an error $digest already in progress when calling $scope.$apply(). I also tried $timeout() but it doesn't update the view.
controller that handles that behavior is:
angular.module('myApp').controller('ObjectCtrl', ['$scope', 'user', 'object', '$routeParams', '$location', '$uibModal',
function ($scope, user, object, $routeParams, $location, $uibModal, displayToken) {
$scope.object = {
user_id: user.currentUser
}
$scope.create_object = function() {
var promise = object.create($scope.object);
promise.then(function(data){
var token = data.data.token;
var modalInstance = $uibModal.open({
animation: $scope.animationsEnabled,
templateUrl: '/app/views/modal_submit_token.html',
controller: 'ObjectCtrl',
resolve: {
displayToken: function () {
$scope.object.token = token;
}
}
});
});
};
}]);
And on my html,
<p><b>{{ object.token }}</b></p>
To pass the parameter you need to use resolve and inject the items in controller
$scope.Edit = function (Id) {
var modalInstance = $modal.open({
templateUrl: '/app/views/admin/addeditphone.html',
controller: 'EditCtrl',
resolve: {
editId: function () {
return Id;
}
}
});
}
Now if you will use like this:
app.controller('EditCtrl', ['$scope', '$location'
, function ($scope, $location, editId)
in this case editId will be undefined. You need to inject it, like this:
app.controller('EditCtrl', ['$scope', '$location', 'editId'
, function ($scope, $location, editId)
Now it will work smooth, I face the same problem many time, once injected, everything start working!
Font: Pass parameter to modal

angular.js routing and stateparams

I'm trying to modify standard user module of meanjs. I added a simple route:
state('users', {
url: '/users/:username',
templateUrl: 'modules/users/views/view-profile.client.view.html'
});
And in my view:
data-ng-controller="ViewProfileController" data-ng-init="findUser()"
I also injected $stateParams to my controller. So in my ViewProfileController - findUser function, when I write this:
console.log($stateParams.username)
I expect to get username parameter. But it returns undefined.
When I set the route this way,
state('users', {
url: '/users/:username',
template: function ($stateParams){
return $stateParams.username;
}
});
it returns username. I don't know what is wrong or missing. Any ideas?
edit: this was my full controller code
'use strict';
angular.module('users').controller('ViewProfileController', ['$scope', '$http', '$stateParams', '$location', 'Users', 'Authentication',
function($scope, $http, $location, Users, Authentication, $stateParams) {
$scope.user = Authentication.user;
$scope.findUser = function () {
console.log($stateParams);
...
};
}
]);
Your dependencies don't match up - the list of dependencies need to match the parameters in the controller function in the same order:
'use strict';
angular.module('users')
.controller('ViewProfileController', ['$scope', '$http', '$stateParams', '$location', 'Users', 'Authentication',
function($scope, $http, $stateParams, $location, Users, Authentication) {
$scope.user = Authentication.user;
$scope.findUser = function () {
console.log($stateParams);
};
}
]);
I should use controller instead of template.
Replace into you code the template: to the follow snippet:
controller: function($stateParams){
console.log('username: '+$stateParams.username);
}
You can see a complete example of this feature here

Categories

Resources