AngularJS - Creating shorthand routes with $route.routes - javascript

Plnkr
I am migrating AngularJS from 1.1.5 to 1.2.27. In the older version, I was able to use shorthand routes i.e.,
var app = angular.module('app', []);
app.config(['$routeProvider', function($routeProvider){
$routeProvider
.when('/show/:list/:type', {templateUrl: 'product.html', controller: 'product_controller'})
.otherwise({redirectTo: '/show/product'});
}]);
app.controller('app_controller', ['$route', function($route){
$route.routes['/show/product'] = {
redirecTo: 'show/product/active'
};
$route.routes['/show/user'] = {
redirecTo: 'show/user/active'
};
}]);
In the above code, when the user enter a url as 'show/product', it redirects to the route 'show/product/active' which was happening in 1.1.5 but this doesn't seems to be works in 1.2.X.
Do you have any idea, why it is not working?
I have a solution in my mind,
app.run(['$rootScope', function($rootScope){
$rootScope.$on('$routeChangeStart', function(event, current_route, previous_route){
//do the conditional redirection using $location.path();
}
}]);
Does this idea looks meaningful and will it work, any suggestion or help?

Related

AngularJs directive not working/visible

I'm just getting started with AngularJs. And I'm trying to implement a login directive. But I don't see the output? I've no errors in my console.
My application structure:
(index.html is not visible)
login.directive.js :
(function() {
'use strict';
angular
.module('lnjapp.login',[])
.directive('login', login);
function login() {
var directive = {
template: '<p>test</p>',
//restrict: 'E',
Controller: LoginController,
controllerAs: 'vm'
};
return directive;
}
})();
app.js :
(function () {
'use strict';
angular.module('lnjapp', ['ngRoute', 'ngCookies', 'angular.filter','lnjapp.login','lnjapp.config'])
.constant('GLOBALS', {
url:'http://domain.dev/api/v1/'
});
$(document).ready(function() {
$.material.init();
});
})();
app/pages/login.html:
<login></login>
--EDIT--
login.controller.js:
(function() {
'use strict';
angular.module('lnjapp.login',[])
.controller('LoginController', LoginController);
function LoginController()
{}
})();
route-config.js:
angular
.module('lnjapp.config',[])
.config(config);
function config($routeProvider) {
$routeProvider
.when('/', {
templateUrl: '/app/pages/login.html'
});
}
What am I doing wrong here?
You are creating your lnjapp.login twice, once in login.directive.js and again in login.controller.js. The second time the module is created, it overwrites the first, and whatever was created in the first file will no longer be accessible.
You should always only create a module once, and get the already created module to add additional features in all other cases.
Set (create): angular.module('lnjapp.login',[])
Get (consume): angular.module('lnjapp.login')
For more info and other best practices, see John Papa's excellent Angular Style Guide.

Reading $Cookies in AngularJS from a method

I am really new with AngularJS and I have been working in an example for few days
https://github.com/cornflourblue/angular-registration-login-example. The thing is that im trying to read a cookie that i sent from server, and in that example the angular-cookie library is so old like (1.2) so i replaced it with the newest one. The problem comes when im trying to access to the run method, i've no access to $cookies var, i tried to inject it without injecting.
I actually have no idea what's happening. So if you could help me a bit (&& ||) recommend me newest and nicer examples would be awesome.
(function () {
'use strict';
var app = angular
.module('app', ['ngRoute', 'ngCookies'])
.config(config)
.run(run);
config.$inject = ['$routeProvider', '$locationProvider'];
function config($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
controller: 'HomeController',
templateUrl: 'AngularJS/home/home.view.html',
controllerAs: 'vm'
})
.when('/login', {
controller: 'LoginController',
templateUrl: 'AngularJS/login/login.view.html',
controllerAs: 'vm'
})
.when('/register', {
controller: 'RegisterController',
templateUrl: 'AngularJS/register/register.view.html',
controllerAs: 'vm'
})
.otherwise({ redirectTo: 'AngularJS/login' });
}
run.$inject = ['$rootScope', '$location', '$http'];
function run($rootScope, $location, $http, $cookies) {
//I want to use $cookies here, but i canno't seem a possible way.
// keep user logged in after page refresh
$rootScope.globals = $cookies.get('globals') || {};
if ($rootScope.globals.currentUser) {
$http.defaults.headers.common['Authorization'] = 'Basic ' + $rootScope.globals.currentUser.authdata; // jshint ignore:line
}
$rootScope.$on('$locationChangeStart', function (event, next, current) {
// redirect to login page if not logged in and trying to access a restricted page
var restrictedPage = $.inArray($location.path(), ['/login', '/register']) === -1;
var loggedIn = $rootScope.globals.currentUser;
if (restrictedPage && !loggedIn) {
$location.path('/login');
}
});
}
})();
Sorry for my poor skills in English... (Not my mothertoungue) :ยท)
Thanks alot.
You forgot to add $cookies to the run.$inject array.
Moreover, defining .$inject arrays is optional as long as you use the standard dependencies names in your component functions' parameters. Here removing your .$inject definitions should leave you with a lighter and functional application.

Why is AngularJS router not triggering?

I'm trying to trigger a controller for this URL http://crm.dev/accounts, I'm just using an anonymous function in this example for the controller, but the alert inside doesn't get triggered. I can't figure out why, guess it is something stupid I'm missing?
I don't want to use a template or view, I just need to get my controller fired.
Please note that I've already set $locationProvider.html5Mode(true);.
'use strict';
angular.module('crm', [
'ngSanitize',
'ngRoute',
'angularMoment',
'ui.bootstrap',
'ui.select',
'ui.bootstrap.datetimepicker'
]);
angular.module('crm').config(function(uiSelectConfig) {
uiSelectConfig.theme = 'bootstrap';
});
angular.module('crm').constant('angularMomentConfig', {
preprocess: 'utc',
timezone: 'Europe/Berlin'
});
angular.module('crm').config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
$routeProvider.
when('/accounts', {
controller: function($scope) {
alert('TEST');
}
}).
otherwise({
redirectTo: '/'
});
// enable html5Mode for pushstate ('#'-less URLs)
$locationProvider.html5Mode(true);
$locationProvider.hashPrefix('!');
}]);
you need to have a
<ng-view></ng-view>
in your main template, otherwise routing system won't work

Multiple Controllers for one view angularjs

I would like to know if it is possible to use multiple controllers for a single url view using angluarjs, I have not been able to find much documentation on this. I would like to use a controller on all pages to switch the page header title, but some pages already contain a controller
app.js
subscriptionApp.config(['$routeProvider',function($routeProvider){
$routeProvider.
when('/billinginfo',{templateUrl:'views/billing-info.html', controller:'billingInfoController'}).
when('/orderreview',{templateUrl:'views/order-review.html', controller:'billingInfoController'}).
when('/subscribed',{templateUrl:'views/subscribed.html', controller:'subscribedTitle'}).
//EXAMPLE: HOW COULD I ADD TWO CONTROLLERS TO SAME PAGE??? THIS DOES NOT WORK
when('/subscribe',{templateUrl:'views/subscribe.html', controller:'subscriptionController', 'testControllerTitle'}).
when('/unsubscribed',{templateUrl:'views/cancelconfirm.html', controller:'unsubscribedTitle'}).
when('/redirectBack',{templateUrl:'views/redirect-to-app.html'}).
when('/redirectHandler',{templateUrl:'views/redirect-handler.html',controller:'redirectController'}).
when('/error',{templateUrl:'views/error.html', controller:'messageController'}).
otherwise({redirectTo:'/subscribe'});
}]);
EDIT
I am trying to add a title controller to each page view:
function testControllerTitle($rootScope, $scope, $http) { $rootScope.header = "Success!"; }
If I add this controllers to the pages that don't already have a controller it works, if there is another controller in place I can't make this work.
<h1 ng-bind="header"></h1>
Yes, controllers and templates are independent, check this http://jsbin.com/wijokuca/1/
var app = angular.module("App", ['ngRoute']);
app.config( function ( $routeProvider ) {
$routeProvider
.when('/a', {templateUrl: 'this.html', controller: "aCtrl"})
.when('/b', {templateUrl: 'this.html', controller: "bCtrl"})
.when('/c', {templateUrl: 'that.html', controller: "bCtrl"})
.otherwise({redirectTo: '/a'});
});
app.controller('aCtrl', function ($scope) {
$scope.all = [1,2,3];
});
app.controller('bCtrl', function ($scope) {
$scope.all = [4,5,6];
});

Angular route config not working in 1.2.3

I have a code based on Angular js framework from google.
The code define some routing and associate views to the url path.
the code is like this
var profileModule = angular.module('profileModule', ['ngResource']);
profileModule.config(function ($routeProvider) {
$routeProvider
.when('/', {
controller: 'profileController',
templateUrl: 'Partials/profileList.html'
})
.otherwise({ redirectTo: '/' });
$routeProvider.when('/profile/:profileId', {
templateUrl: 'Partials/profileDetail.html',
controller: 'profileDetailController'
});
});
profileModule.controller('profileController', function($scope, profileFactory) {
$scope.profiles = [];
function init() {
$scope.profiles = profileFactory.query();
}
init();
});
profileModule.factory('profileFactory', function ($resource) {
return $resource("api/profiles/:Id", { Id: "#Id" }, { "update": { method: "PUT" } });
});
The code was using version 1.1.5 of Angular, and it was working fine.
But then I tried to use the newer version 1.2.3
and the code is not working on this version.
it is giving this error
[$injector:unpr] Unknown provider: $routeProvider
I looked on example on how to use routeProvider in 1.2.3
and I found this example from the web site
profileModule.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.....
I tried this , but still the same error
I am using Angular from the CDN network , and specifically from here
http://code.angularjs.org/1.2.3/angular-route.js
You need to depend on the ngRoute module as well:
var profileModule = angular.module('profileModule', ['ngResource', 'ngRoute']);
Since Angular v 1.2, they've separated the routing into a separate file, so you have to include it in your code and then inject it into your module.
You can find the latest version here (angular-route.js):
http://code.angularjs.org/1.2.3/

Categories

Resources