Ionic app global AppCtrl, is this right? - angularjs

This is the third time this week that I reach some one code that user an AppController like this in it app
<body ng-app="app" ng-controller="AppCtrl">
<div id="inner" ng-view="" ></div>
</body>
And in the controller they redirect to the different parts of the app,
like this
.controller("AppController",function({$location}{
if(isUserAthenticated){
$location.path("/home");
}else{
$location.path("/login")
}
});
Is this the correct way to do this. Because it doesn't seem to me. I see this approach very hacky and there should be a right way to do it.
Can you guys let me know the best and recommended way to handle this kind of scenarios?
UPDATE: Routing config
// delete $httpProvider.defaults.headers.common["Access-Control-Request-Headers"];
$routeProvider
.when('/app', {
templateUrl: 'views/login.html',
controller: 'AppCtrl'
}).
when('/privados', {
templateUrl: 'views/privados.html',
controller: 'PrivadosCtrl as ctrl'
}).
when('/mensaje/:id', {
templateUrl: 'views/mensaje.html',
controller: 'MensajeCtrl as ctrl'
}).
when('/grupales', {
templateUrl: 'views/grupales.html',
controller: 'GrupalesCtrl as ctrl'
}).
when('/comunicados', {
templateUrl: 'views/comunicados.html',
controller: 'ComunicadosCtrl as ctrl'
}).
when('/contactos', {
templateUrl: 'views/contactos.html',
controller: 'ContactosCtrl'
}).
when('/perfil', {
templateUrl: 'views/perfil.html',
controller: 'PerfilCtrl'
}).
when('/principal', {
templateUrl: 'views/principal.html',
controller: 'PrincipalCtrl as ctrl'
}).
when('/nmensaje/:type', {
templateUrl: 'views/nmensaje.html',
controller: 'NMensajeCtrl as ctrl'
}).
when("/user/password",{
templateUrl:"views/passwordreset.html",
controller: "ResetPasswordCtrl as ctrl"
}).
otherwise({
redirectTo: '/app'
});

The best way that I found to manage the Authentication in an Angular App is the following:
Inside the .config() method of your Angular App:
//this event will be fired in every location change.
$rootScope.$on('$routeChangeSuccess', function(e, toState, fromState) {
if (toState.loginRequired) {
if (!isUserAthenticated()) {
e.preventDefault();
$location.path('/login');
}
}
});
then in your routes you could specify which one required the login:
when('/nmensaje/:type', {
templateUrl: 'views/nmensaje.html',
controller: 'NMensajeCtrl as ctrl',
loginRequired: true
}).
when("/user/password",{
templateUrl:"views/passwordreset.html",
controller: "ResetPasswordCtrl as ctrl",
loginRequired: true
}).
Furthermore you can create an Angular Factory to manage the authentication status of the user.
Note that with this approach you wont need an AppCtrl.

Related

How to add Dynamic templateUrl

I have web application where I need to load a template with different parameters like.
.when('/form/:ProjectID/:FormID', {
templateUrl: 'partials/Form.ashx?fid=' + FormID,
controller: 'FormController'
})
I am not able to get the above code working. Can someone tell me how I can fix this issue? I am new to AngularJS and not an expert.
This is the full code.
var app = angular.module('MyApp', ['ui.grid', 'ngSanitize', 'angularTrix', 'ui.codemirror', 'ngRoute']);
app.config(function ($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: 'partials/Home.ashx',
controller: 'HomeController'
})
.when('/project/:ProjectID', {
templateUrl: 'partials/Projects.ashx',
controller: 'ProjectController'
})
.when('/form/:ProjectID/:FormID', {
templateUrl: 'partials/Form.ashx?fid=1',
controller: 'FormController'
})
.otherwise({ redirectTo: '/home' });
});
We can use $stateParams and templateProvider to load dynamic templateurl
.state('general', {
url: '/{type}',
//templateUrl: 'pages/home.html',
templateProvider: ['$stateParams', '$templateRequest',
function($stateParams, $templateRequest)
{
var tplName = "pages/" + $stateParams.type + ".html";
return $templateRequest(tplName);
}
],
// general controller instead of home
//controller: 'homeController',
controller: 'generalController',
controllerAs: 'ctrl'

$scope not updated - controller specification

I have the following routing:
app.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/panel', {
templateUrl: 'views/panel.html'
}).
when('/make', {
templateUrl: 'views/makePanel.html',
controller: 'painelCtrl'
}).
when('/paneluser', {
templateUrl: 'views/panelUser.html',
controller: 'userCtrl'
}).
when('/paneluserblocks', {
templateUrl: 'views/userPanels.html',
controller: 'userCtrl'
}).
when('/registred', {
templateUrl: 'views/registredPanels.html'
}).
when('/color', {
templateUrl: 'views/color.html',
controller: 'alarmCtrl'
}).
otherwise('/', {
templateUrl: 'Index.html',
});
}]);
When I specify a controller for a particular html template, my $scope variables are no longer updated in the view.
When I pull out the controller specification for a particular route, things return to normal.
The controller 'userCtrl' is accessed through $location and is intended for ordinary users. In turn, 'Ctrl panel' is the primary controller assigned to admin users.
Could anyone tell me what's going on?
I haven't all information, but it's working in my demo.
Config
var app = angular.module('app',['ngRoute']);
app.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/panel', {
templateUrl: 'views/panel.html'
}).
when('/make', {
templateUrl: 'views/makePanel.html',
controller: 'painelCtrl'
}).
otherwise('/', {
templateUrl: 'Index.html',
});
}]);
Definition of your controller:
app.controller('painelCtrl',painelCtrl);
painelCtrl.$inject = ['$scope'] //and more if you need $http, services, ...
function painelCtrl($scope){
$scope.hello= "hello world"
}
HTML
<h1>{{hello}}</h1>
I'm sorry for the igenuidade. I believed that the pages being in the same controller, I would never miss the reference:
When ('/panel', {
TemplateUrl: 'views/panel.html',
Controller: 'panelCtrl'
}).
When ('/make', {
TemplateUrl: 'views/makePanel.html',
Controller: 'panelCtrl'
}). cotinue...
In fact, views panel.html and makePanel.html will use the same controller structure, however we will have one instance for each view (variables will be reseted).
In my case I used factory functions to solve the problem. Every time I mute controller, I store the information of interest through a set () and get it through a get ();
app.factory("MonitorService", function () {
var info;
function set(data) {
info = data;
}
function get() {
return info;
}
return {
set: set,
get: get
}
});

Adding fusioncharts with angularjs gives : inject modulerr error

I want to add fusioncharts to my angularjs app. I have followed this link:
http://www.fusioncharts.com/blog/2015/03/angular-fusioncharts/
But as soon as I add ng-fusioncharts to my app.js as:
var app = angular.module('myApp',['ngRoute', 'firebase','ng-fusioncharts']);
app.config(function($routeProvider){
$routeProvider
.when('/', {
controller: 'OrgListController',
templateUrl: 'views/organization/list.html'
})
.when('/add_org', {
controller: 'OrgAddController',
templateUrl: 'views/organization/org_add.html'
})
.when('/edit_org/:id', {
controller: 'OrgEditController',
templateUrl: 'views/organization/org_edit.html'
})
.when('/add_access_point', {
controller: 'AccessPointAdd',
templateUrl: 'views/access_points/access_add.html'
})
.when('/edit_access_point/:id', {
controller: 'AccessPointEdit',
templateUrl: 'views/access_points/access_edit.html'
})
.when('/add_user', {
controller: 'UserAdd',
templateUrl: 'views/users/user_add.html'
})
.when('/edit_user/:id', {
controller: 'UserEdit',
templateUrl: 'views/users/user_edit.html'
})
.otherwise({
redirectTo: '/'
});
});
Nothing gets displayed and my whole project doesn't work. Viewing in console says :
error: inject modulerr.................
Somebody please suggest how to add multiple dependencies in one module?
You need to have fusion-chart.js inorder to inject ng-fusioncharts
var app = angular.module('HelloApp', ["ng-fusioncharts"])
DEMO

Angularjs routing OTHERWISE causes 404

I have a single page application where I route to different pages based on url address, I would like to redirect to Homepage when user enters non existing page in the url, so I use otherwise statement, however it causes 404 error, here is my routing config.:
myApp.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
$routeProvider.
when('/', {
redirectTo: '/products'
}).
when('/products/:id?', {
templateUrl: 'partials/products.html',
controller: 'ProductsController'
}).
when('/orders/:id?', {
templateUrl: 'partials/orders.html',
controller: 'OrdersController'
}).
when('/auto', {
templateUrl: 'partials/AutoComplete.html',
controller: 'TypeaheadCtrl'
}).
otherwise({ redirectTo: '/' });
$locationProvider.html5Mode(true);
}]);
EDIT:
Changed it as suggested below buts till the same affect, when I type non existing page it goes to Error 404 instead of /products
myApp.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
$routeProvider.
when('/', {
redirectTo: '/products'
}).
when('/products', {
templateUrl: 'partials/products.html',
controller: 'ProductsController'
}).
when('/products/:id?', {
templateUrl: 'partials/products.html',
controller: 'ProductsController'
}).
when('/orders/:id?', {
templateUrl: 'partials/orders.html',
controller: 'OrdersController'
}).
when('/auto', {
templateUrl: 'partials/AutoComplete.html',
controller: 'TypeaheadCtrl'
}).
otherwise({ redirectTo: function () { return '/' } });
$locationProvider.html5Mode(true);
}]);
You don't need the when('/'... and the otherwise as they essentially do the same thing.
The otherwise is a catchall to get anything that isn't matched so you don't need to route the '/' specifically.
$routeProvider.
when('/products/:id?', ...).
when('/orders/:id?', ...).
when('/auto', ...).
otherwise({
redirectTo: '/products'
});
EDIT The problem is that redirecting to '/products' won't match '/products/:id'. You'll need to add another route like as follows:
when('/products', {
templateUrl: 'partials/products.html',
controller: 'ProductsController'
})

Angular Route Infinite Loop

For some reason when I have a dynamic property in my route and access that page I get stuck in an infinite loop where that page will continuously request itself.
.config(["$routeProvider", "$locationProvider", function($routeProvider, $locationProvider)
{
$locationProvider.html5Mode(true);
$routeProvider.when("/", {
templateUrl: "pages/index.html",
controller: "IndexCtrl"
}).when("/listhome", {
templateUrl: "pages/listhome.html",
controller: "ListHomeCtrl"
}).when("/profile", {
templateUrl: "pages/profile.html",
controller: "ProfileCtrl"
}).when("/newlist", {
templateUrl: "pages/newlist.html",
controller: "NewListCtrl"
}).when("/userlists/:id", {
templateUrl: "pages/userlists.html",
controller: "UserListsCtrl"
}).otherwise({
redirectTo: "/"
});
The route I'm looking at is the /userlists/:id route. The controller for that route is-
TopTenApp.controller("UserListsCtrl", ["$scope","$routeParams", function($scope, $routeParams)
{
console.log($routeParams);
$scope.lists = [];
}]);
And when I access /userlists/9 I see-
Object {id: "9"}
Being logged every 3 seconds and the page freezes. This seems to happen whenever there is a forward slash after the location ("/userslists/" instead of "/userlists").
Does anyone know the cause of this?
Silly me I realized the problem. I guess it makes sense but the template url needs to have a forward slash in front of it when the page is multiple "directories" deep.
.config(["$routeProvider", "$locationProvider", function($routeProvider, $locationProvider)
{
$locationProvider.html5Mode(true);
$routeProvider.when("/", {
templateUrl: "/pages/index.html",
controller: "IndexCtrl"
}).when("/listhome", {
templateUrl: "/pages/listhome.html",
controller: "ListHomeCtrl"
}).when("/profile", {
templateUrl: "/pages/profile.html",
controller: "ProfileCtrl"
}).when("/newlist", {
templateUrl: "/pages/newlist.html",
controller: "NewListCtrl"
}).when("/userlists/:id", {
templateUrl: "/pages/userlists.html",
controller: "UserListsCtrl"
}).otherwise({
redirectTo: "/"
});
}]);
Hopefully that helps someone else with a similar problem.

Resources