Here is my :
config.router.js
app.config(['$stateProvider', '$urlRouterProvider', '$controllerProvider', '$compileProvider', '$filterProvider', '$provide', '$ocLazyLoadProvider', 'JS_REQUIRES',
function ($stateProvider, $urlRouterProvider, $controllerProvider, $compileProvider, $filterProvider, $provide, $ocLazyLoadProvider, jsRequires) {
app.controller = $controllerProvider.register;
app.directive = $compileProvider.directive;
app.filter = $filterProvider.register;
app.factory = $provide.factory;
app.service = $provide.service;
app.constant = $provide.constant;
app.value = $provide.value;
// LAZY MODULES
$ocLazyLoadProvider.config({
debug: false,
events: true,
modules: jsRequires.modules
});
// APPLICATION ROUTES
// -----------------------------------
$urlRouterProvider.otherwise('/login/signin');
//
// Set up the states
$stateProvider.state('app', {
url: "/app",
templateUrl: "assets/views/app.html",
resolve: loadSequence('modernizr', 'moment', 'angularMoment', 'uiSwitch', 'perfect-scrollbar-plugin', 'toaster', 'ngAside', 'vAccordion', 'sweet-alert', 'chartjs', 'tc.chartjs', 'oitozero.ngSweetAlert', 'chatCtrl'),
abstract: true
}).state('app.dashboard', {
url: "/dashboard",
templateUrl: "assets/views/dashboard.html",
resolve: loadSequence('jquery-sparkline', 'dashboardCtrl'),
title: 'Dashboard',
ncyBreadcrumb: {
label: 'Dashboard'
}
})
...
loginCtrl.js
app.controller('LoginCtrl', ["$scope", "alert", "auth", "$state", "$auth", "$timeout", function ($scope, alert, auth, $state, $auth, $timeout) {
$scope.submit = function () {
$auth.login({
email: $scope.email,
password: $scope.password
})
.then(function(res) {
var message = 'Thanks for coming back ' + res.data.user.email + '!';
if (!res.data.user.active)
{$auth.logout();
message = 'Just a reminder, please activate your account soon :)';}
alert('success', 'Welcome', message);
return null;
})
.then(function() {
$timeout(function() {
$state.go('main');
});
})
.catch(handleError);
} // submit function for login view
function handleError(err) {
alert('warning', 'oops there is a problem!', err.message);
}
}]);
main.js
var app = angular.module('myApp', ['my-app']);
app.run(['$rootScope', '$state', '$stateParams',
function ($rootScope, $state, $stateParams) {
// Attach Fastclick for eliminating the 300ms delay between a physical tap and the firing of a click event on mobile browsers
FastClick.attach(document.body);
// Set some reference to access them from any scope
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
// GLOBAL APP SCOPE
// set below basic information
$rootScope.app = {
name: 'My App',
author: 'example author',
description: 'My Platform',
version: '1.0',
year: ((new Date()).getFullYear()),
isMobile: (function () {
var check = false;
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
check = true;
};
return check;
})()
};
$rootScope.user = {
name: 'Peter',
job: 'ng-Dev'
};
}]);
the problem is when I add ng-controller="loginCtrl" to my login div on the html file for login, it works. But I have another div just below the login div:
<div class="copyright" >
{{app.year}} © {{ app.name }} by {{ app.author }}.
</div>
This doesn't work! however, I have a similar one above the login div, it works:
<div class="logo">
<img ng-src="{{app.layout.logo}}" alt="{{app.name}}"/>
</div>
where is the problem? How to address it?
thanks
if you are using angular ui-router, it's not neccessary to add ng-controller="loginCtrl" to your DIVs manually, instead add controller property in your $stateProvider.state
example:
.state('app.dashboard', {
url: "/dashboard",
templateUrl: "assets/views/dashboard.html",
title: 'Dashboard',
controller: 'dashboardCtrl',
resolve: {
deps: ['$ocLazyLoad', function ($ocLazyLoad) {
return $ocLazyLoad.load('path/to/your/controller.js');
}]
},
ncyBreadcrumb: {
label: 'Dashboard'
}
})
when you change your state usually views change to, that's the point right? setting controllers on the fly might not work as you expect.
checkout documentation
Related
https://plnkr.co/edit/PWuKuVw9Dn9UJy6l8hZv?p=preview
I have 3 modules, routerApp, tickers and tags. Basically trying to rebuild my app out of smaller mini-apps.
The routerApp template contains the 2 directives for the other modules.
Expected
When you login, then click on the Count button in the tickers.component, I want to send the counter var into the tags.component $scope via $state.go.
Result
Nothing happens. No $state/variable update in the tags.component
Plnkr app.js code:
// TICKERS app module
var tickers = angular.module('tickers', ['ui.router'])
tickers.config(function($stateProvider) {
const tickers = {
name: 'tickers',
url: '/tickers',
parent: 'dashboard',
templateUrl: 'tickers-list.html',
bindToController: true,
controllerAs: 'tik',
controller: function() {
}
}
$stateProvider
.state(tickers);
})
tickers.component('tickersModule', {
templateUrl: 'tickers-list.html',
controller: function($scope, $state) {
console.log('Tickers init')
$scope.counter = 0;
$scope.increase = function() {
$scope.counter++;
console.log('increase', $scope.counter)
$state.go('dashboard.tags', { counter: $scope.counter });
}
}
})
// TAGS app module
var tags = angular.module('tags', ['ui.router'])
tags.config(function($stateProvider) {
const tags = {
name: 'tags',
url: '/tags?counter',
parent: 'dashboard',
params: {
counter: 0
},
templateUrl: 'tags-list.html',
bindToController: true,
controllerAs: 'tags',
controller: function($state) {
}
}
$stateProvider
.state(tags);
})
tags.component('tagsModule', {
templateUrl: 'tags-list.html',
controller: function($scope, $state) {
// Expecting this to update:
console.log('Tags init', $state)
$scope.counter = $state.params.counter;
}
})
// MAIN ROUTERAPP module
var routerApp = angular.module('routerApp', ['ui.router', 'tickers', 'tags']);
routerApp.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/login');
const login = {
name: 'login',
url: '/login',
templateUrl: 'login.html',
bindToController: true,
controllerAs: 'l',
controller: function($state) {
this.login = function() {
$state.go('dashboard', {})
}
}
}
const dashboard = {
name: 'dashboard',
url: '/dashboard',
templateUrl: 'dashboard.html',
controller: function() {
}
}
$stateProvider
.state(login)
.state(dashboard);
})
dashboard.html
<div class="jumbotron text-center">
<h1>The Dashboard</h1>
</div>
<div class="row">
<tickers-module></tickers-module>
<tags-module></tags-module>
</div>
The function in the tickers component that is trying to update the $state of the tags component:
$scope.increase = function() {
$scope.counter++;
console.log('increase', $scope.counter)
$state.go('dashboard.tags', { counter: $scope.counter });
}
Also tried: $state.go('tags', { counter: $scope.counter });
Finally the tags.component.
Note that here I'm not seeing the $scope.counter update nor the controller for the component getting refreshed due to a state change.
tags.component('tagsModule', {
templateUrl: 'tags-list.html',
controller: function($scope, $state) {
console.log('Tags init', $state)
$scope.counter = $state.params.counter;
}
})
Is the way I am architecting this going to work? What am I missing?
Update: Added some $rootScope events to watch for $state changes, hope this helps:
This is after clicking the login button and going from the login state to the dashboard state, but still nothing for clicking on the Count button.
So, it looks like you're properly passing the parameters in your $state.go call.
I think the issue here is that you're not properly handling the state parameters you're passing from the tickers component to the tags component.
Try injecting $stateParams into your tags component and pull the parameters off that object, for example (in your tags controller):
$scope.counter = $stateParams.counter;
Figured it out!
https://plnkr.co/edit/CvJLXKYh8Yf5npNa2mUh?p=preview
My problem was that in the $state object tags, I was using the same template as the tags.component.
Instead I needed to change it to something like <p>{{ counter }}</p>
var tags = angular.module('tags', ['ui.router'])
tags.config(function($stateProvider) {
const tags = {
name: 'tags',
url: '/tags',
parent: 'dashboard',
params: {
counter: 0
},
template: '<p>{{ counter }}</p>',
bindToController: true,
controller: function($scope, $state) {
console.log('tags state object', $state)
$scope.counter = $state.params.counter;
}
}
$stateProvider
.state(tags);
})
tags.component('tagsModule', {
templateUrl: 'tags-module-template.html',
controller: function($scope, $state) {
}
})
Then in my tags-module.template.html I needed to add a <div ui-view></div>
<div class="jumbotron text-center">
<h2>Tags list</h2>
<div ui-view></div> // <- here and this is where the $state object updates
{{ counter }}
</div>
I am new to AngularJS and I am using Angular UI-Router for my SPA.
What I am trying to do is to update the Parent View values from the Child View. I have gone through the UI-Router documentation for Nested Views and Multiple Views but couldn't find a way to update the values.
My use case is, Parent view will be the Header and every time a Child View changes via the State Transition I want to update the header value which is part of the Parent View.
Code :
HTML File -
<div ui-view></div>
JS File where Angular UI-Routing configuration happens -
angular.module('myApp', ['ui.router']).config(['$stateProvider', '$routeProvider',
function($stateProvider, $routeProvider) {
$stateProvider
.state('main', {
resolve: {
resA: function() {
return {
'value': 'Hello !!'
};
}
},
controller: function($scope, resA) {
$scope.resA = resA.value;
},
abstract: true,
url: '/main',
template: '<h1>{{resA}}</h1>' +
'<div ui-view></div>'
})
.state('main.one', {
url: '/one',
views: {
'#main': {
template: "Im View One"
}
},
resolve: {
resB: function(resA) {
return {
'value': resA.value + ' from One'
};
}
},
controller: function($scope, resA, resB) {
$scope.resA = resB.value;
}
}).state('main.two', {
url: '/two',
views: {
'#main': {
template: '<div ui-view="sub1"></div>' +
'<div ui-view="sub2"></div>'
},
'sub1#main.two': {
template: "Am awesome"
},
'sub2#main.two': {
template: "Am awesome two/too"
}
},
resolve: {
resC: function(resA) {
return {
'value': resA.value + ' from Two'
};
}
},
controller: function($scope, resA, resC) {
$scope.resA = resC.value;
}
});
}]).run(['$rootScope', '$state', '$stateParams', function($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
$state.transitionTo('main.two');
}]);
Here is the JSFiddle Link of the same code snippet.
There are muliple ways you can update the parent scope.
Using controllerAs
https://jsfiddle.net/9n7wrevt/17/
controller: function($scope, resA) {
this.resA = resA.value;
},
controllerAs: 'main'
referring parent as below
controller: function($scope, resB) {
$scope.main.resA = resB.value;
}
Using $parent
https://jsfiddle.net/9n7wrevt/18/
controller: function($scope, resB) {
$scope.$parent.resA = resB.value;
}
Better way(highly recommended) is to use $scope $emit, $on to communicate between controllers.
https://jsfiddle.net/9n7wrevt/19/
I am using ionic framework. I am trying to load login page as first page but cant see its just getting an empty page.
My code looks like
app.js:
app.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('app', {
url: "/app",
abstract: true,
templateUrl: "templates/menu.html",
controller: 'AppCtrl'
})
and controller:
.controller('AppCtrl', function ($scope, $state, $ionicModal) {
$ionicModal.fromTemplateUrl('templates/login.html', function(modal) {
$scope.loginModal = modal;
},
{
scope: $scope,
animation: 'slide-in-up',
focusFirstInput: true
}
);
//Be sure to cleanup the modal by removing it from the DOM
$scope.$on('$destroy', function() {
$scope.loginModal.remove();
});
.controller('LoginCtrl', function ($scope, $state, AuthenticationService) {
$scope.message = "";
$scope.user = {
username: null,
password: null
};
$scope.login = function () {
AuthenticationService.login($scope.user);
};
$scope.$on('event:auth-loginRequired', function (e, rejection) {
console.log('handling login required');
$scope.loginModal.show();
});
$scope.$on('event:auth-loginConfirmed', function () {
$scope.username = null;
$scope.password = null;
$scope.loginModal.hide();
});
But still cant see it.
my app looks like
https://github.com/keithdmoore/ionic-http-auth but without the home page.
Thnx!
try to change your app.config section.
app.config(function ($stateProvider) {
$stateProvider.otherwise({ redirectTo: '/login' });
$stateProvider
.state('app', {
url: "/app",
abstract: true,
templateUrl: "templates/menu.html",
controller: 'AppCtrl'
}).state('login', {
url: "/login",
templateUrl: "login.html page url",
controller: 'login controller'
}));
don't need to write any code appcontroller'. Whenever you run the application the url path is should be empty. So this line $stateProvider.otherwise({ redirectTo: '/login' }); helps to open the login screen.
I'm trying to use $translate.use() in my ui-router config file routes.js so I can switch toggle language with a state but I get an
Uncaught Error: [$injector:modulerr] Failed to instantiate module frontApp due to:
Error: [$injector:unpr] Unknown provider: $translate
Here is my file.
'use strict';
(function() {
angular.module('frontApp')
.run(['$rootScope', '$state', '$stateParams', function($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
}]
)
.config(['$urlRouterProvider', '$stateProvider', '$locationProvider', '$translate', function($urlRouterProvider, $stateProvider, $locationProvider, $translate){
$urlRouterProvider
.otherwise('/');
$stateProvider
.state('home', {
url: '/',
templateUrl: '/views/home.html',
controller: 'HomeCtrl'
})
.state('home.rules', {
url: '^/rules',
templateUrl: '/views/rules.html'
})
.state('home.terms', {
url: '^/terms',
templateUrl: '/views/terms.html'
})
.state('home.faq', {
url: '^/faq',
templateUrl: '/views/faq.html'
})
.state('language', {
controller: function() {
console.log('ok');
$translate.use(($translate.use() === 'fr') ? 'en' : 'fr' );
}
});
$locationProvider.html5Mode(true);
}]);
}());
I also have a translation.js file containing my translations and when not trying to inject and use $translate.use() in the above routes.js file I have no problem using it using the TranslateController:
'use strict';
(function() {
angular.module('frontApp')
.config(['$translateProvider', function($translateProvider) {
$translateProvider
.translations('fr', {
language: 'English',
otherLanguage: 'en',
cssClass: 'french',
linkHome: 'Accueil',
linkRules: 'Règlement',
linkTerms: 'Termes et conditions',
linkFAQ: 'FAQ',
})
.translations('en', {
language: 'Français',
otherLanguage: 'fr',
cssClass: 'english',
linkHome: 'Home',
linkRules: 'Rules',
linkTerms: 'Terms and conditions',
linkFAQ: 'FAQ',
});
$translateProvider.preferredLanguage('fr');
}])
.controller('TranslateController', ['$translate', '$scope', '$location', function ($translate, $scope, $location) {
// The URLs need to be updated
var host = $location.host();
if ( host === 'localhost' || host === '0.0.0.0') {
$translate.use('fr');
}
else if (host === 'localhost-en') {
$translate.use('en');
}
$scope.switchLanguage = function() {
$translate.use(($translate.use() === 'fr') ? 'en' : 'fr' );
};
}]);
}());
Here is the app.js:
'use strict';
angular
.module('frontApp', [
'ui.router',
'ngAnimate',
'ngCookies',
'ngResource',
'ngSanitize',
'ngTouch',
'pascalprecht.translate'
]);
What am I missing ? Many thanks for your time and help.
Solution here would be to move the DI definition of the '$translate' - where it belongs, i.e. into controller definition:
.state('language', {
// instead of this
// controller: function() {
// use this
controller: function($translate) {
console.log('ok');
$translate.use(($translate.use() === 'fr') ? 'en' : 'fr' );
}
});
or even better controller: ['$translate', function($translate) {... }]
Why is current solution not working? Well, let's have a look at this extract from the above code:
// I. CONFIG phase
.config(['$urlRouterProvider', '$stateProvider', '$locationProvider', '$translate'
, function($urlRouterProvider, $stateProvider, $locationProvider, $translate){
...
$stateProvider
...
.state('language', {
// II. CONTROLLER - RUN phase
controller: function() {
As we can see, we ask for $translate above in the config phase. So we recieve the provider... to be configured.
But the controller definition is expecting to be provided with a servic - already configured. It must have its own DI ... because it will be executed in a RUN phase...
Also check this Q & A for more details about provider in config vs run phase - Getting Error: Unkown provider: $urlMatcherFactory
I'm trying to create an SPA where you have to be logged in to access almost everything. So naturally, the default screen you see is the login screen. However, after a user has logged in, no matter what the ui-sref is, ui-router redirects to the login page (even when the user is authenticated). Here is my ui-router code:
(function () {
'use strict';
angular
.module('app', ['ui.router', 'satellizer'])
.config(function ($stateProvider, $urlRouterProvider, $authProvider, $httpProvider, $provide) {
$httpProvider.interceptors.push(['$q', '$injector', function($q, $injector){
return {
responseError: function (rejection) {
var $state = $injector.get('$state');
var rejectionReasons = ['token_not_provided', 'token_expired', 'token_absent', 'token_invalid'];
angular.forEach(rejectionReasons, function (value, key) {
if (rejection.data.error === value) {
localStorage.removeItem('user');
$state.go('auth');
}
});
return $q.reject(rejection);
},
response: function(response) {
var authorization = response.headers('authorization');
if(authorization !== null) {
authorization = authorization.substr(7).trim();
//console.log(authorization);
var $auth = $injector.get('$auth');
$auth.setToken(authorization);
}
return response;
}
}
}]);
$authProvider.loginUrl = 'mingdaograder/api/authenticate';
$stateProvider
.state('users', {
url: '/users',
templateUrl: 'views/userView.html',
controller: 'UserController as user'
})
.state('subjects', {
url: '/users/:user_id/subjects',
templateUrl: 'views/subjectsView.html',
controller: 'SubjectsCtrl as subjectsCtrl'
})
.state('subject', {
url: '/users/:user_id/subjects/:subject_id',
templateUrl: 'views/subjectView.html',
controller: 'SubjectCtrl as subjectCtrl'
})
.state('auth', {
url: '/auth',
templateUrl: 'views/authView.html',
controller: 'AuthController as auth'
});
//.state('otherwise', {
// url: '*path',
// templateUrl: 'views/authView.html',
// controller: 'AuthController as auth'
//});
//$urlRouterProvider.otherwise('/auth');
$urlRouterProvider.otherwise(function($injector, $location) {
console.log("Could not find " + $location);
$location.path('/auth');
});
})
.run(function ($rootScope, $state, $log) {
$rootScope.$on('$stateChangeStart', function (event, toState) {
console.log(toState.name);
var user = JSON.parse(localStorage.getItem('user'));
if (user) {
$rootScope.authenticated = true;
$rootScope.currentUser = user;
}
}
);
}
);
})();
Anytime I try to use $state.go(any state name here) or even type the address into the address bar, I am always redirected to the auth state. On the console the message is "Could not find http://localhost/#/" for every single route. I can type in http://localhost/#/users/5/subjects and I get the same message.
Here is one of my controllers doing a redirect:
(function () {
'use strict';
angular
.module('app')
.controller('AuthController', AuthController);
function AuthController($auth, $state, $http, $rootScope, $log) {
var vm = this;
vm.loginError = false;
vm.loginErrorText;
vm.login = function () {
var credentials = {
username: vm.username,
password: vm.password
};
$auth.login(credentials).then(function () {
return $http.get('api/authenticate/user');
}, function (error) {
vm.loginError = true;
vm.loginErrorText = error.data.error;
}).then(function (response) {
var user = JSON.stringify(response.data.user);
localStorage.setItem('user', user);
$rootScope.authenticated = true;
$rootScope.currentUser = response.data.user;
//$log.info('From AuthCtrl: ' + $rootScope.currentUser.id);
$state.go('subjects', {user_id:$rootScope.currentUser.id});
});
}
}
})();
Any ideas what I'm doing wrong? Thanks a lot for your time.
Update: Ok, I haven't found a way to fix it but I think I may have found a possible cause. It seems to only happen for the routes with parameters. For example, if I go to the users state, whose path is /users, there is no redirect. However, if I go to the subjects state, whose path is /users/:user_id/subjects, it does redirect. It's like the Url matching service can't recognize that /users/5/subjects matches /users/:user_id/subjects, so redirects. Any ideas how to work around this?
I found I didn't have a '/' at the beginning of my initial state url. Every time I navigated to the state, the missing '/' seemed to push it into the stateProvider.otherwise.
state1: 'opportunity'
state1Url : '/opportunity/' <== added initial forward slash to make it work.
state2: 'opportunity.create'
state2Url : 'create/'
The first path to be recognised will be the selected as the current location. This means that the order of your route definitions is crucially important. In your case you only have a single catch-all otherwise route definition and since all routes match this then all routes are directed to your login page ignoring any other route definitions you may have, including all your stateProvider state definitions.
One way to fix this is to remove the urlRouterProvider route definition altogether and instead use the *path syntax provided by ui-router to create an alternative otherwise state (which must be defined last for the same reasons given above).
Therefore your code might look something like this:
$stateProvider
.state('auth', {
url: '/auth',
templateUrl: 'views/authView.html',
controller: 'AuthController as auth'
})
.state('users', {
url: '/users',
templateUrl: 'views/userView.html',
controller: 'UserController as user'
})
.state('subjects', {
url: '/users/:user_id/subjects',
templateUrl: 'views/subjectsView.html',
controller: 'SubjectsCtrl as subjectsCtrl'
})
.state('subject', {
url: '/users/:user_id/subjects/:subject_id',
templateUrl: 'views/subjectView.html',
controller: 'SubjectCtrl as subjectCtrl'
})
.state("otherwise", {
url: "*path",
templateUrl: 'views/authView.html',
controller: 'AuthController as auth'
});
From experience, this is either due to the / missing at either the beginning or the end of the url route property definition.
Make sure for parent routes to add the initial forward slash to your routes.
.state('checkers', {
url: '/checkers/',
templateUrl: 'checkers.html',
controller: 'CheckersController',
title: 'Checker',
})
(function () {
'use strict';
angular
.module('app', ['ui.router', 'satellizer'])
.config(function ($stateProvider, $urlRouterProvider, $authProvider, $httpProvider, $provide) {
$httpProvider.interceptors.push(['$q', '$injector', function($q, $injector){
return {
responseError: function (rejection) {
var $state = $injector.get('$state');
var rejectionReasons = ['token_not_provided', 'token_expired', 'token_absent', 'token_invalid'];
angular.forEach(rejectionReasons, function (value, key) {
if (rejection.data.error === value) {
localStorage.removeItem('user');
$state.go('auth');
}
});
return $q.reject(rejection);
},
response: function(response) {
var authorization = response.headers('authorization');
if(authorization !== null) {
authorization = authorization.substr(7).trim();
//console.log(authorization);
var $auth = $injector.get('$auth');
$auth.setToken(authorization);
}
return response;
}
}
}]);
$authProvider.loginUrl = 'mingdaograder/api/authenticate';
$stateProvider
.state('users', {
url: '/users',
templateUrl: 'views/userView.html',
controller: 'UserController as user'
})
.state('subjects', {
url: '/users/:user_id/subjects',
templateUrl: 'views/subjectsView.html',
controller: 'SubjectsCtrl as subjectsCtrl'
})
.state('subject', {
url: '/users/:user_id/subjects/:subject_id',
templateUrl: 'views/subjectView.html',
controller: 'SubjectCtrl as subjectCtrl'
})
.state('auth', {
url: '/auth',
templateUrl: 'views/authView.html',
controller: 'AuthController as auth'
});
//.state('otherwise', {
// url: '*path',
// templateUrl: 'views/authView.html',
// controller: 'AuthController as auth'
//});
//$urlRouterProvider.otherwise('/auth');
$urlRouterProvider.otherwise(function($injector, $location) {
console.log("Could not find " + $location);
$location.path('/auth');
});
})
.run(function ($rootScope, $state, $log) {
$rootScope.$on('$stateChangeStart', function (event, toState) {
console.log(toState.name);
var user = JSON.parse(localStorage.getItem('user'));
if (user) {
$rootScope.authenticated = true;
$rootScope.currentUser = user;
}
}
);
}
);
})();