I'm trying to configure my route in such a way to redirect to the login page if user is not logged. This is my code:
angular.module('witBiz.services', []);
angular.module('witBiz.controllers', ['witBiz.services']);
var witBizModule = angular.module('witBiz', ['ngRoute' , 'witBiz.controllers', 'witBiz.services' ]);
witBizModule.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/login', {templateUrl: 'resources/views/login.html', controller: 'LoginController'});
$routeProvider.when('/index', {templateUrl: 'resources/views/index.html', controller: 'IndexController'});
$routeProvider.otherwise({redirectTo: 'resources/views/index.html'});
}])
.run(['$rootScope', 'checkLogin', function($rootScope, checkLogin ,$routeProvider ) {
$rootScope.$on('$routeChangeSuccess', function () {
if (checkLogin())
$location.url("/index");
})
}])
.factory('checkLogin', function(){
return function() {
//perform real logic here
return true;
}
})
where basically I declare modules and services. Now the problem is $location is not defined so I get error.
I tried to inject $location as dependency like this but I got undefined injection (injpt):
.run(['$rootScope', 'checkLogin', '$location', function($rootScope, checkLogin ,$location) {
$rootScope.$on('$routeChangeSuccess', function () {
if (checkLogin())
$location.url("/ciao");
})
}])
So I'm wondering how I can use the builtin $location services inside my "run" method...why can I inject it as a dependency as $rootScope or checkLogin?!
I'm using angular 1.2.0 rc2.
Thanks
Here is a working example http://plnkr.co/edit/gf5LhTjqhz4MoZfVcqIt?p=preview
Couldn't reproduce the error with $location not working inside .run
Related
How do I pass the resolve validToken value to my controller?
Config:
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/recover/:token', {
templateUrl: 'recover.html',
controller: 'recoverCtrl',
resolve: {
validToken : function(){
return "INVALID TOKEN"
}
}
});
}])
Controller:
.controller('recoverCtrl', ['$location','$scope','$http', '$routeParams', '$rootScope',
function($location,$scope,$http,$routeParams,$rootScope,validToken) {
console.log(validToken);
// Rest of controller code.
}
]);
I would like to do this without removing the []'s so the code could eventually be minifed. The below example is working as I expected so I know that all of my code it working, I'm just not sure what I should add to the above code to make it function similarly.
.controller('recoverCtrl', function($location,$scope,$http,$routeParams,$rootScope,validToken) {
console.log(validToken);
//Other code
});
Figured it out thanks to Etsus.
I just needed to add the object key as a string while injecting and it was able to determine that it was a resolve key
.controller('recoverCtrl', ['$location','$scope','$http', '$routeParams', '$rootScope', 'validToken', function ($location, $scope, $http, $routeParams, rootScope, validToken) {
console.log(validToken);
}]);
I have a rails application which use AngularJS and I have a problem, the problem is that I want redirect to a certain state after a form is submited, but in the chrome's console I have a ReferenceError: $state is not defined and nothing happens.
This is my controller.
angular.module('myapp')
.controller('CreatePollCtrl', ['$scope', 'Restangular', '$state',
function($scope, Restangular) {
$scope.addPoll = function() {
if ($scope.allow_anonymous_answer == null)
$scope.allow_anonymous_answer = false
var poll = {title: $scope.title, description: $scope.description, allow_anonymous_answer: $scope.allow_anonymous_answer, initial_message: $scope.initial_message, final_message: $scope.final_message};
Restangular.all('polls').post(poll).then(function(response) {
$state.go('dashboard');
});
};
}]);
What can I do?, is $state correctly injected?
you forgot add $state to function()
angular.module('myapp')
.controller('CreatePollCtrl', ['$scope', 'Restangular', '$state',
function($scope, Restangular, $state) {
Add $state as a parameter to your function, like $scope.addPoll = function($state) {...}
I'm writing routing logic using ngRoute of angular JS. The following is my code.
index.js
(function() {
'use strict';
function config($routeProvider, $httpProvider, cfpLoadingBarProvider, $tooltipProvider) {
$routeProvider.otherwise({redirectTo: '/404'});
$httpProvider.defaults.withCredentials = false;
$httpProvider.defaults.headers.common['content-type'] = "application/json";
}
angular
.module('pacman', ['ngCookies', 'ngRoute', 'ui.bootstrap', 'ui.validate',
'angular-cache', 'angular-loading-bar', 'angular-md5', 'rt.iso8601', 'ngAnimate']
)
.config(['$routeProvider', '$httpProvider', 'cfpLoadingBarProvider', '$tooltipProvider', config])
.run(['$rootScope', '$location', '$modalStack', '$cookies']);
})();
app.controller.js
(function() {
'use strict';
function config($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'app/components/landingpage/landingpage.html',
controller: 'appController'
});
}
function appController($scope, $rootScope, $location) {
$scope.submitLogin = function() {
alert("Successfully loggedIn");
};
}
angular
.module('pacman')
.controller('appController', ['$scope', '$rootScope', '$location', appController])
.config(['$routeProvider', config]);
})();
notFound.controller.js
(function() {
'use strict';
function config($routeProvider) {
$routeProvider.when('/404', {
templateUrl: 'app/components/notFound/404page.html',
controller: 'notFoundController'
});
}
function notFoundController($scope, $rootScope, $location) {
debugger;
}
angular
.module('pacman')
.controller('notFoundController', ['$scope', '$rootScope', '$location', notFoundController])
.config(['$routeProvider', config]);
})();
My code is a simple app. I'm trying to load different controllers based on routes. However at the time of loading the app, in the last controller's '$routeProvider' it throws an error
Uncaught Error: [ng:areq] Argument 'fn' is not a function, got string
http://errors.angularjs.org/1.4.8/ng/areq?p0=fn&p1=not%20a%20function%2C%20got%20string
I have no clue how to figure out the problem. Any leads would be appreciated.
The following is my library bundle order.
'node_modules/jquery/dist/jquery.js',
'node_modules/angular/angular.js',
'node_modules/angular-route/angular-route.js',
'node_modules/jquery.transit/jquery.transit.js',
'node_modules/angular-cache/dist/angular-cache.js',
'node_modules/angular-cookies/angular-cookies.js',
'node_modules/angular-loading-bar/build/loading-bar.js',
'node_modules/angular-ui-validate/dist/validate.js',
'node_modules/chart.js/Chart.js',
'node_modules/angular-md5/angular-md5.js',
'node_modules/angular-iso8601/dist/angular-iso8601.js',
'node_modules/angular-animate/angular-animate.js',
'node_modules/angular-chart.js/dist/angular-chart.js',
'node_modules/rx/dist/rx.all.js',
'node_modules/angular-ui-bootstrap/ui-bootstrap-tpls.js',
'node_modules/bootstrap/dist/js/bootstrap.js'
Kindly help.
Issue is in your index.js where you define the run method on your angular app.
angular
.module('pacman', []) // removed dependencies for brevity
.run(['$rootScope', '$location', '$modalStack', '$cookies']);
The last argument in the array passed to run should be a function but you forgot to pass a function. Change your run to add some implementation like below or remove the run if you don't see any use for it.
angular.module('pacman', []) // removed dependencies for brevity
.run(['$rootScope', '$location', '$modalStack', '$cookies',
function($rootScope,$location,$modalStack,$cookies){
// some statements here
}]);
Angular JS file declaration must come before the jquery in your index.html
'node_modules/angular/angular.js',
'node_modules/jquery/dist/jquery.js',
I have an rest api, in which the api is sending instruction to redirect (301 is being sent).
And I have my angular js code like this:
var request = $http.post(LOGIN_URL,{username:'tes',password:'test'})
request.success(function(html)
{
if(html.failure) {
console.log("failure")
$scope.errorMessage = html.failure.message
}
else {
console.log("Success here....")
$location.path("route")
}
})
I can see in the browser log that it is coming in the else part ( Success here..... is being printed). But the url is not changed. $location.path doesnt do anything; I have also tried $location.url which also results the same thing.
And also I'm injecting the $location to my controller.
Where I'm making mistake?
Thanks in advance.
Try something like this
$location.path("/myroute")
You have to have a ng-view on the page as well.
Also make sure you have a corresponding view with that name
and when you're registering your controller you have the '$location' var being injected in the declaration of your controller like this example:
controllers.controller('MyCtrl', ['$scope', '$route', '$location', 'MYService',
function($scope, $route, $location, MyService) {
// ... controller code
}])
also you might want to debug your route changing to see what is happening with a location change listener, like in this example:
return app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/home', {
templateUrl: 'partials/home.html',
controller: 'MyCtrl'
}).
when('/login', {
templateUrl: 'partials/login.html',
controller: 'LoginCtrl'
}).
when('/error/:errorId', {
templateUrl: 'partials/error.html',
controller: 'ErrorCtrl'
}).
otherwise({
redirectTo: '/home'
});
}]).run(function($rootScope, $injector, $location) {
$rootScope.$on("$locationChangeStart", function(event, next, current) {
console.log('current=' + current.toString());
console.log('next=' + next.toString());
});
});
});
I'm having issues using oclazyload with $stateProvider.
I have specified that the controller .js should be loaded in the router config, and it does,' but it's not available to use as an ng-controller attribute in the file loaded in templateURL.
ui-route config:
core
.run(
[ '$rootScope', '$state', '$stateParams',
function ($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
}
]
)
.config(
[ '$stateProvider', '$urlRouterProvider',
function ($stateProvider, $urlRouterProvider) {
console.info('Routing ...');
$urlRouterProvider
.otherwise('/app/dashboard');
$stateProvider
.state('app', {
abstract: true,
url: '/app',
templateUrl: 'templates/app.html',
})
.state('app.orders', {
abstract: true,
url: '/orders',
templateUrl: 'templates/orders/orders.html',
})
.state('app.orders.index', {
url: '/index',
templateUrl: 'templates/orders/index.html',
resolve: {
deps: ['$ocLazyLoad',
function( $ocLazyLoad ){
console.info('Path ot order controller in route config',Momento.paths.js + 'controllers/orders/index.js');
return $ocLazyLoad.load([
Momento.paths.js + 'controllers/orders/index.js'
])
}
]
}
})
}
]
)
;
And my templateURL file starts:
<div class="" id="" ng-controller="OrdersIndexController">...</div>
But when it loads, console throws the error:
<info>orders/index controller loaded controllers/orders/index.js:3
<info>Now I've finished loading the controller/order/index.js config/ui-router.js:69
<info>orders template loaded VM30437:1 (<-- this is the app.orders abstract template with ui-view directive ready for app.orders.index view)
<error>Error: [ng:areq] Argument 'OrdersIndexController' is not a function, got undefined
... <trace>
So the file is loaded correctly by lazyload, confirmed by console output above and network tab in developer tools, but it's not available in the templateURL to use as controller? Does it need to be aliased either in router config using controller:'' key or in template? Does it need to be specifically attached to the (only) module in this app?
What am I missing?
PS: confirming that the name of the controller is in fact OrdersIndexController:
core
.controller('OrdersIndexController', [
'Model', '$scope', '$window',
function( Model, $scope, $window){
console.info("OrdersIndexController fired");
}
]);
You have to register your controller with
angular.module("myApp").controller
Working
angular.module("myApp").controller('HomePageController', ['$scope', function ($scope) {
console.log("HomePageController loaded");
}]);
Not working
var myApp = angular.module("myApp")
myApp.controller('HomePageController', ['$scope', function ($scope) {
console.log("HomePageController loaded");
}]);
Inside the function function($ocLazyLoad){} you must to declare the name of module that contains the controller and the name of file "to lazy load"
function( $ocLazyLoad ){
return $ocLazyLoad.load(
{
name: 'module.name',
files: ['files']
}
);
}
If you use the current documented way for ocLazyLoad 1.0 -> With your router
...
resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
loadMyCtrl: ['$ocLazyLoad', function($ocLazyLoad) {
// you can lazy load files for an existing module
return $ocLazyLoad.load('js/AppCtrl.js');
}]
}
then in js/AppCtrl.js
You have something like this:
angular.module("myApp").controller('DynamicNew1Ctrl', ['$scope', function($scope) {
$scope.name = "Scoped variable";
console.log("Controller Initialized");
}]);
Note that with angular.module("myApp") you are attaching the new controller to an existing module, in this case the mainApp, so any of new dynamic controllers can use the app dependencies.
but you can define a new module an inject your dependencies, as described here, the later is used commonly when you estructure your app with a plugin architecture and you want to isolate the dynamic modules so they only have access to some especific dependencies