(AngularJS v1.2.28 - angular-ui-router v0.2.13
In my index.html I have the following:
<div class="wrapper" ui-view></div>
In my app.js I have my stateProvider set up as:
$urlRouterProvider.otherwise('/app/search');
$stateProvider.state("app", {
url: '/home',
controller: 'MainCtrl',
templateUrl: 'views/main.html'
}).state('app.search', {
resolve: {
categories: function ($q, $stateParams, LiveOak) {
var deferred = $q.defer();
LiveOak.readMembers('/liveoak/storage/categories', {
success: function (categories) {
deferred.resolve(categories);
},
error: function (error) {
console.error(error);
}
});
return deferred.promise;
}
},
url: '/search',
templateUrl: 'views/search.html',
controller: 'SearchCtrl'
}
).state('app.subjects', {
url: '/subjects/:id',
abstract:true,
templateUrl: '<ui-view/>'
}
).state('app.subjects.default', {
resolve: {
subjects: function ($q, $stateParams, LiveOak) {
var deferred = $q.defer();
var categoryId = $stateParams.id;
var query = {
categoryId : categoryId
};
LiveOak.readMembers('/liveoak/storage/subjects', {
query: query,
success: function (subjects) {
console.log("subjects resolved")
deferred.resolve(subjects);
},
error: function (error) {
console.error(error);
}
});
return deferred.promise;
},
instructors: function ($q, $stateParams, LiveOak) {
}
},
url: '',
templateUrl: 'views/subject.html',
controller: 'SubjectCtrl'
}).state('app.subjects.authors', { //THIS IS NOT RECOGNIZED
resolve: {
authors: function ($q, $stateParams, LiveOak) {
var deferred = $q.defer();
var subjectId = $stateParams.id;
var query = {
query.subjectId : subjectId
};
LiveOak.readMembers('/liveoak/storage/authors', {
query: query,
success: function (authors) {
deferred.resolve(authors);
},
error: function (error) {
console.error(error);
}
}
);
return deferred.promise;
}
},
url: '/subjects/:id/authors/',
templateUrl: '../views/subjects.authors.html',
controller: 'AuthorsCtrl'
}
);
}]);
I am wrestling with the state: app.subjects.authors. Right now app.search and app.subjects work. However, when I try to go the the state: app.subjects.authors it is not even recognized. I set up up a state app.subject as abstract, so hopefully app.subjects.authors wouldn't be overridden by app.subjects. Anyone see anything out of the ordinary?
Thanks for the help!!
My subject.html looks like this:
<div ng-repeat="subject in subjects" class="mdl-cell mdl-cell--4-col">
<a href="#/app/subjects/{{subject.categoryId}}/authors">
<span>{{subject.name}}</span>
</a>
</div>
Just change templateUrl: to template:. You don't need abstract:.
.state('app.subjects', {
url: '/subjects/:id',
template: '<ui-view/>'
})
You shall have:
url: '/authors',
Instead of:
url: '/subjects/:id/authors/',
Because url is relative. So the url of child state is continuation of parent state's url. So authors state will match following url:
/home/subjects/:id/authors
Related
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;
In my main module i have used ui-bootstrap modal for checking login authentication.From run block i have called to loginModal service but it is giving Error
TypeError: loginModal is not a function
angular.module('myApp', ['ui.router', 'ui.bootstrap', 'loginServices','leaveServices']). config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/home');
$stateProvider.
state('home', {
url:'/home',
data: {
requireLogin: false
},
views: {
'': {
templateUrl: 'partials/templates/assets/home.html'
}
}
}).
state('home.about', {
url: '/about',
templateUrl: 'partials/templates/assets/about.html'
}).
state('home.contact', {
url: '/contact',
templateUrl: 'partials/templates/assets/contactUs.html'
}).
state('/login', {
url: '/login',
data: {
requireLogin: false
},
templateUrl: 'partials/login.html',
controller: loginUserController
}).
state('/register', {
url:'/register',
data: {
requireLogin: false
},
templateUrl: 'partials/registerUser.html',
controller: registerController
}).
state('/getAllUsers', {
url: '/getAllUsers',
data: {
requireLogin: false
},
templateUrl: 'partials/getAllUsers.html',
controller: getUsersController
}).
state('/updateUser', {
url : '/updateUser/:id/:name',
data: {
requireLogin: true
},
params: {'id':null, 'name':null},
templateUrl: 'partials/updateUser.html',
controller: updateUserController
}).
state('/userLeave', {
url : '/userLeave:name',
data: {
requireLogin: true
},
params: {'name': null},
templateUrl: 'partials/userLeave.html',
controller: userLeaveController
}).
state('/leaveRequest', {
url : '/leaveRequest',
data: {
requireLogin: true
},
templateUrl: 'partials/leaveRequest.html'
});
}])
.run(function ($rootScope, $state, loginModal) {
$rootScope.$on('$stateChangeStart', function (event, toState, toParams) {
var requireLogin = toState.data.requireLogin;
console.log('going to state '+toState.name);
if (requireLogin && typeof $rootScope.currentUser === 'undefined') {
event.preventDefault();
loginModal().then(function () {
return $state.go(toState.name, toParams);
})
.catch(function () {
return $state.go('/login');
});
}
});
})
.factory('loginModal', function ($modal, $rootScope) {
function assignCurrentUser (user) {
$rootScope.currentUser = user;
return user;
}
return function() {
var instance = $modal.open({
templateUrl: 'partials/login.html',
controller: loginUserController
});
return instance.result.then(assignCurrentUser);
}
});
here login controller
loginUserController.$inject = ['$scope','$http', 'loginFactory', '$location', '$state'];
function loginUserController($scope,$http,loginFactory,$location, $state){
$scope.validateLogin = function(name,password){
$http.get("http://localhost:3010/validateLogin?userName="+name+"&password="+password)
.then(function(response) {
if(response.data.length != 0) {
console.log("logged user data is "+JSON.stringify(response.data));
$state.transitionTo('/userLeave', {name: name});
// $scope.$close(response);
}
else
$scope.inValidUser = 'Invalid User';
});
};
$scope.cancel = $scope.$dismiss;
}
Could be because you're using an Angular service which expects a constructor which in turn, should not be returning something.
Try changing to a factory, eg
.factory('loginModal', ...
I am a Web Developer with experience over 5 years. Nowadays I learnt MEAN-stack web site developing way and began to start MEAN-stack project. Then I have some problems in front-end section(angular control managing).
My main problem is my angular controller js file causes 2 browser error. like as following.
The first error is as follows:
aangular.js:68 Uncaught Error: [$injector:nomod] Module 'app' is not available!
You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.(…)(anonymous function)
# angular.js:68(anonymous function)
# angular.js:2082ensure
# angular.js:2006module
# angular.js:2080(anonymous function)
# UsersService.js:4(anonymous function)
# UsersService.js:111
The second error is as follows:
angular.js:13920 Error: [ng:areq] Argument 'Users.Controller' is not a function, got undefined
My front-end code structure is the following.
controllers
users.controller.js, account.controller.js, projects.controller.js and so on.
services
UsersService.js, AccountService.js and so on
app.js (middleware section)
views
index.html, htmls corresponding to each controller js
lets take a look code in detail.
App.js file:
(function () {
angular.module('app', ['ui.router'])
.config(config)
.run(run);
function config($stateProvider, $urlRouterProvider) {
// default route
$urlRouterProvider.otherwise("/");
$stateProvider
.state('home', {
url: '/',
template: '<h1>Unpasan Admin Page!</h1>',
controller: 'Users.Controller',
controllerAs: 'vm',
//data: { activeTab: 'home' }
})
.state('account', {
url: '/account',
templateUrl: 'views/account.html',
controller: 'Accounts.Controller',
controllerAs: 'vm',
data: { activeTab: 'account' }
})
.state('client', {
url: '/client',
templateUrl: 'views/client.html',
controller: 'Clients.Controller',
controllerAs: 'vm',
data: { activeTab: 'client' }
})
.state('user', {
url: '/user',
templateUrl: 'views/user.html',
controller: 'Users.Controller',
controllerAs: 'vm',
data: { activeTab: 'client' }
})
.state('project', {
url: '/project',
templateUrl: 'views/project.html',
controller: 'Projects.Controller',
controllerAs: 'vm',
data: { activeTab: 'project' }
});
}
UsersService.js:
(function () {
angular
.module('app')
.factory('UserService', function(){
var service = {};
service.GetCurrent = GetCurrent;
service.GetAll = GetAll;
service.GetById = GetById;
service.GetByUsername = GetByUsername;
service.Create = Create;
service.Update = Update;
service.Delete = Delete;
return service;
function GetCurrent() {
return $http.get('/api/users/current').then(handleSuccess, handleError);
}
function GetAll() {
return $http.get('/api/users').then(handleSuccess, handleError);
}
function GetById(_id) {
return $http.get('/api/users/' + _id).then(handleSuccess, handleError);
}
function GetByUsername(username) {
return $http.get('/api/users/' + username).then(handleSuccess, handleError);
}
function Create(user) {
return $http.post('/api/users', user).then(handleSuccess, handleError);
}
function Update(user) {
return $http.put('/api/users/' + user._id, user).then(handleSuccess, handleError);
}
function Delete(_id) {
return $http.delete('/api/users/' + _id).then(handleSuccess, handleError);
}
// private functions
function handleSuccess(res) {
return res.data;
}
function handleError(res) {
return $q.reject(res.data);
}
});
})();
users.controller.js
angular.module('app',[]).controller('UsersController', ['$scope, UserService', function($scope, UserService){
$scope.users = null;
initController();
console.log('Users.Controller:initController');
function initController() { // get current user
UserService.getAllUser().then(function (users) {
$scope.users = users;
});
}
function saveUser() {
UserService.Update(vm.user)
.then(function () {
FlashService.Success('User updated');
})
.catch(function (error) {
FlashService.Error(error);
});
}
function deleteUser() {
UserService.Delete(vm.user._id)
.then(function () {
// log user out
$window.location = '/login';
})
.catch(function (error) {
FlashService.Error(error);
});
}
}] );
When I clicked elements of sidebar in index.html, should be exchanged content of 'ui-view' tag.
The error message mentioned above is case of clicked users 'ui tag'.
Instead of controller: 'Users.Controller', it should be controller: 'UsersController' (see object passed into the state definition for 'home'). You should pass in the name of the controller (UsersController), not the file name (users.controller).
I'm working on authentication with angularjs, so after connecting my user I want to redirect him to the home page:
$scope.submit = function(user) {
var request = {
method: 'POST',
url: 'http://localhost:9001/signIn',
headers: {
'Content-Type': 'application/json'
},
data: {
"email": user.email,
"password": user.password,
"rememberMe": true
}
};
$http(request).then(function(data) {
$location.path('/home');
}, function(error) {
console.log(error);
});
};
here is my configuration:
app.config(function($urlRouterProvider, $stateProvider, $httpProvider, $authProvider) {
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home', {
url: '/home',
templateUrl: '/home',
controller: 'HomeCtrl',
resolve: {
authenticated: function($q, $location, $auth) {
var deferred = $q.defer();
if (!$auth.isAuthenticated()) {
$location.path('/signIn');
} else {
deferred.resolve();
}
return deferred.promise;
}
}
})
.state('signIn', {
url: '/signIn',
templateUrl: '/signIn',
controller: 'SignInCtrl'
});
});
I tried this:
$http(request).then(function(data) {
$scope.$evalAsync(function() {
$location.path('/home');
});
console.log(data);
}, function(error) {
console.log(error);
});
also :
$location.path('/home');
$location.replace();
Neither of the above work, any help is greatly appreciated.
The home state resolver function fails to resolve or reject the $q.defer promise when $auth.isAuthenticated() returns false. This will cause the promise to hang and create a memory leak.
//ERRONEOUS CODE
$stateProvider
.state('home', {
url: '/home',
templateUrl: '/home',
controller: 'HomeCtrl',
resolve: {
authenticated: function($q, $location, $auth) {
var deferred = $q.defer();
if (!$auth.isAuthenticated()) {
$location.path('/signIn');
//FAILS to resolve or reject promise
} else {
deferred.resolve();
}
return deferred.promise;
}
}
})
Instead return a rejection when not authenticated:
$stateProvider
.state('home', {
url: '/home',
templateUrl: '/home',
controller: 'HomeCtrl',
resolve: {
authenticated: function($q, $location, $auth) {
//var deferred = $q.defer();
if ($auth.isAuthenticated()) {
return $q.resolve("AUTHENTICATED");
};
//otherwise
return $q.reject("NOT AUTHENTICATED");
})
}
})
When a resolver function returns a rejected promise, the state change will be prevented and the $stateChangeError event will be broadcast on $rootScope.
I have tried several method but $state.go() is not refreshing my page.Here is my controller. All process works but i cannot reload the browse page using $state.go() function.
angular.module('kawaadi.controllers', [])
.controller('AppCtrl', function ($scope, Service, $ionicLoading, $ionicModal, $ionicPopup, $timeout, $state, $http,$location) {
$scope.loginData = {};
$ionicModal.fromTemplateUrl('templates/login.html', {
scope: $scope
}).then(function (modal) {
$scope.modal = modal;
});
$scope.closeLogin = function () {
$scope.modal.hide();
};
$scope.login = function () {
$scope.modal.show();
};
$scope.logout = function () {
localStorage.setItem("token", "");
$state.go('login');
};
$scope.statusData = function (pid, uid, status) {
$ionicLoading.show({
template: 'Processing...'
});
Service.change_status(pid, uid, status, $http).success(function (data) {
if (data.status === 'success' && data.notification_status === 'success') {
$ionicLoading.hide();
var alertPopup = $ionicPopup.alert({
title: 'Success!',
template: 'Successfully changed and notification has been send!'
});
} else if (data.status === 'success' && data.notification_status === 'failure') {
$ionicLoading.hide();
var alertPopup = $ionicPopup.alert({
title: 'Success!',
template: 'Successfully changed but failed to send notification!!'
});
}
alertPopup.then(function (res) {
if (res == true) {
$state.go('app.browse');
}
});
}).error(function (data) {
var alertPopup = $ionicPopup.alert({
title: 'Process failed!',
template: 'Some thing went wrong!'
});
});
}
})
and here is my url router
.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('login', {
url: '/login',
templateUrl: 'templates/auth.html',
controller: 'LoginCtrl'
})
.state('app', {
url: '/app',
templateUrl: 'templates/menu.html',
controller: 'AppCtrl'
})
.state('app.search', {
url: '/search',
views: {
'menuContent': {
templateUrl: 'templates/search.html'
}
}
})
.state('app.browse', {
url: '/browse',
views: {
'menuContent': {
templateUrl: 'templates/browse.html',
controller: 'pickupCtrl'
}
}
})
.state('app.playlists', {
url: '/playlists',
views: {
'menuContent': {
templateUrl: 'templates/playlists.html',
controller: 'PlaylistsCtrl'
}
}
})
.state('app.single', {
url: '/playlists/:playlistId',
views: {
'menuContent': {
templateUrl: 'templates/playlist.html',
controller: 'PlaylistCtrl'
}
}
});
});
Please guide me. Thanks in advance
Please modify all your states as
.state('emailConfirmation',{
cache: false,
url:"/emailConfirmation",
templateUrl:"app/session/emailConfirmation.html",
controller: 'EmailConfirmationCtrl'
})
and to reload the current page please use these command
$state.transitionTo($state.current, $stateParams, {
reload: true,
inherit: false,
notify: true
});
If you want to force reload the current state, then you probably need to use $state.go($state.current.name, $state.params, {reload: true}) as mentioned here
Just Add the following in Your ion-view tag
<ion-view cache-view="false">