AngularJS $location.url() only works on Page Refresh - angularjs

I've created a directive, called admin, which I only want to show if the base URL contains the string admin and then depending on the URL path the directive's view will show different content.
So if the user navigates to admin.example.com they will see the directive's view, they won't see it if they go to just example.com.
I've got it working to an extent, it works when I first load the angularJS app, but not when I click on different pages of the app and load different views and routes.
This is my basic App:
/* Define the `app` module */
var app = angular.module('app', ['ngRoute', 'ngTouch', 'ngAnimate', 'ui.bootstrap', 'ngSanitize']); // TODO: 'ngAnimate', 'ui.bootstrap'
app.config(['$routeProvider','$locationProvider', function($routeProvider, $locationProvider){
$routeProvider
.when('/', {
class: 'home-page',
title: 'Home',
templateUrl: '/app/static/home.html',
controller: 'mainController as mainCtrl'
})
.when('/about', {
class: 'about-page',
title: 'About',
templateUrl: '/app/static/about.html',
controller: 'mainController as mainCtrl'
})
.when('/news/id-:newsId', {
class: 'news-page',
title: 'News',
templateUrl: 'app/components/news/details/newsDetailsView.html',
controller: 'newsDetailsController as newsDCtrl'
})
.otherwise({
class: 'page-not-found',
title: '404 Page Not Found',
templateUrl: '/app/static/404.html',
controller: 'mainController as mainCtrl'
});
// use the HTML5 History API
$locationProvider.html5Mode(true);
}]);
app.run(['$rootScope', function($rootScope) {
$rootScope.$on('$routeChangeSuccess', function (event, current, previous) {
$rootScope.class = current.$$route.class;
$rootScope.title = current.$$route.title;
$rootScope.description = current.$$route.description;
});
}]);
app.controller('adminController', ['$location', function ($location) {
var adminCtrl = this;
adminCtrl.isAdmin = $location.host().includes('admin.example') ? true : false;
adminCtrl.urlPath = $location.url();
}])
app.directive('admin', [function(){
return {
restrict: 'E',
templateUrl: 'app/components/admin-links/adminView.html',
transclude: true,
replace: true,
controller: 'adminController as adminCtrl'
};
}]);
The problem is adminCtrl.urlPath = $location.url(); only updates when I refresh the page, not when I click on the different routes within the app and change the page without refreshing the page.
How can I get this value to update when the user navigates through the different views/routes without refreshing the page?

You need to use $location.path()
This will give you the route paths.
Change
adminCtrl.urlPath = $location.url();
to
adminCtrl.urlPath = $location.path();

Related

How to change URL of the page in AngularJS routing in one controller?

this is the routing configuration:
tapp.config(function ($routeProvider) {
$routeProvider.when('/', {
title: 'Home',
controller: 'tCtrlr',
templateUrl: '../HTML/Index.html',
}),
$routeProvider.when('/Tasks', {
title: 'Tasks',
controller: 'tCtrlr',
templateUrl: '../HTML/Tasks.html',
}),
$routeProvider.when('/MyTasks', {
title: 'My Tasks',
controller: 'tCtrlr',
templateUrl: '../HTML/MyTasks.html',
})
When navigating between the pages the title is not set, I've read some SO threads regarding to this issue, but most assume I have a controller for every page. So how could I get the title property in the when function?
The way I do it is quite simple. In route configuration you define title:
.when('/dashboard', {
title : 'My Dashboard',
templateUrl : 'templates/sections/app-dashboard.html',
controller : 'DashboardController'
})
then you listen $routeChangeSuccess event and just set document.title. In application run block (the best place for this).
app.run(['$rootScope', '$route', function($rootScope, $route) {
$rootScope.$on('$routeChangeSuccess', function() {
document.title = $route.current.title;
});
}]);
The benefit of this approach is that it allows you to avoid one more binding ng-bind="title".

Controller loaded twice using ui-router + custom directive

I am trying to bring to my homepage a custom directive which will print me some output.
In the network tab in my devtools I just saw that my controller loads twice.
controller:
var homeController = function($log,leaguesFactory){
var self = this;
self.leagues = [];
leaguesFactory.loadLeagues()
.then(function(leagues){
self.leagues = leagues.data.Competition;
});
self.message= 'test message';
};
directive:
var leaguesTabs = function(){
return {
restrict : 'E',
templateUrl : 'app/home/leagues-tabs.tpl.php',
scope: {
leagues: '='
},
controller: 'homeController',
controllerAs: 'homeCtrl'
};
};
ui-router states:
$stateProvider
.state('home',{
url : '/',
templateUrl : 'app/home/home.tpl.php',
controller : 'homeController',
controllerAs: 'homeCtrl'
})...
I just want to use my homeCtrl in the directive, but it seems that the state provider loads it also and make it load twice. If I remove the controller from the directive then I don't get access to the homeCtrl, if I remove the homeCtrl from the stateprovider than I don't have access in the home.tpl.php
home.tpl.php:
<div>
<leagues-tabs></leagues-tabs>
</div>
any idea?
Actually problem related to next steps:
ui-router start handling url '/'
ui-router create an instance of 'homeController'
ui-router render the view 'app/home/home.tpl.php'
Angular see usage a custom directive - 'leagues-tabs'
'leagues-tabs' directive create an instance of 'homeController'
'leagues-tabs' render the view 'app/home/home.tpl.php'
You can follow any of next possible solutions:
Change controller for 'leagues-tabs' to something special
Remove controller usage from ui-router state definition
You can try this one http://plnkr.co/edit/LG7Wn5OGFrAzIssBFnEE?p=preview
App
var app = angular.module('app', ['ui.router', 'leagueTabs']);
UI Router
app.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/leagues');
$stateProvider
.state('leagues', {
url: '/leagues',
templateUrl: 'partial-leagues.html',
controller: 'LeaguesController',
controllerAs: 'ctrl'
});
}]);
Controller
app.controller('LeaguesController', ['$http', function($http) {
var self = this;
$http.get('leagues.json').success(function(data){
self.leagues = data;
})
}]);
View
<div>
<league-tabs leagues="ctrl.leagues"></league-tabs>
</div>
Directive
var leagueTabs = angular.module('leagueTabs', []);
leagueTabs.directive('leagueTabs', function(){
return {
restrict : 'E',
templateUrl : 'partial-league-tabs.html',
scope: {
leagues: '='
},
controller: 'LeagueTabsController',
controllerAs: 'leagueTabs'
}
});
leagueTabs.controller('LeagueTabsController', function($scope){
var self = this
$scope.$watch('leagues', function(leagues){
self.leagues = leagues;
})
})
Directive View
<div>
<ul ng-repeat="league in leagueTabs.leagues">
<li>{{league.name}}</li>
</ul>
</div>

How to pass and read multiple params in URL - angularjs

There are 2 views with respective controllers.
The links are in View1.Clicking on this link should load View2 and also read the parameters.
This is what I have tried but the alert says - undefined.
View2 can load with/without params - each case having a different workflow.
View1.html:
<div ng-controller="view1ctrl">
<a href="#/view2/pqid/775/cid/4" >Link1</a>
</div>
app.js:
var app = angular.module('app', ['ngRoute']);
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/view1', {
templateUrl: 'App/views/view1.html',
controller: 'view1ctrl'
})
.when('/view2', {
templateUrl: 'App/views/view2.html',
controller: 'view2ctrl'
})
.when('/view2/:pqid/:cid', {
templateUrl: 'App/views/view2.html',
controller: 'view2ctrl'
})
.otherwise({
redirectTo: '/view1'
});
}]);
view2ctrl.js:
app.controller("view2ctrl", ['$scope','$routeParams',function ($scope, $routeParams) {
var init = function () {
alert($routeParams.pqid);
}
init();
}]);
You are nearly there:
.when('/view2/:pqid/:cid'
maps to a URL in this format :
view2/1234/4567
1234 being the pqid and 4567 the cid.
So your routing, I think is working, just change the link to #/view2/775/4.
Or if you want to keep the same link change your routing to:
#/view2/pqid/:pqid/cid/:cid

AngularJS - How to disable access from URL

I'm working with routes :
App.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/home', {
templateUrl: 'orders/list',
controller: OrderController
});
$routeProvider.when('/editOrder', {
templateUrl: 'addOrder/editOrder',
controller: ActionController
});
$routeProvider.otherwise({redirectTo: '/home'});
I want to navigate to the edit page only when a button is clicked, but this definition allows access via url from browser also. Is it possible to disable access via url ?
You can use $routeChangeStart event to implement custom logic on route to be changed and veto navigation depending on some condition/permission. In the following example you can navigate to /edit route only if you have granted permissions, which you can grant or revoke using PermissionsService service. In the following example you can try to navigate via direct link and see that you are redirected to default route, and when you click Edit button you are redirected to the relevant route. Also, if you are on /edit route and make browser back and forward, you can notice that you can't go back to /edit route.
HTML
Home
Edit
<div ng-view></div>
<button ng-click="edit()">Edit</button>
JavaScript
angular.module('app', ['ngRoute']).
config(['$routeProvider', function($routeProvider){
$routeProvider.when('/home', {
templateUrl: 'list.html',
controller: 'OrderController'
});
$routeProvider.when('/edit', {
templateUrl: 'edit.html',
controller: 'ActionController'
});
$routeProvider.otherwise({redirectTo: '/home'});
}]).
run(['$rootScope', '$location', 'PermissionsService', function($rootScope, $location, PermissionsService) {
$rootScope.edit = function() {
PermissionsService.setPermission('edit', true);
$location.path('/edit');
};
$rootScope.$on("$routeChangeStart", function(event, next, current) {
if (next.templateUrl === "edit.html") {
if(!PermissionsService.getPermission('edit')) {
$location.path('/');
}
PermissionsService.setPermission('edit', false);
}
});
}]).
service('PermissionsService', [function() {
var permissions = {
edit: false
};
this.setPermission = function(permission, value) {
permissions[permission] = value;
}
this.getPermission = function(permission) {
return permissions[permission] || false;
}
}]).
controller('OrderController', [function() {}]).
controller('ActionController', [function() {}]);
Live example here.
You can use the resolve property and set some variable on an external service:
App.factory('editMode', function(){
var editMode = false;
return {
getEditMode: function(){ return editMode; },
setEditMode: function(edit) { editMode = edit; }
}
}
And then on the route:
$routeProvider.when('/editOrder', {
templateUrl: 'addOrder/editOrder',
controller: ActionController,
resolve: function(editMode){
if(!editMode.getEditMode()) {
$location.path( "/" );
}
}
});

Dynamically switch ng-include between controllers

I have the following bit of code for my navigation that I want to update dynamically between pages.
<nav ng-include="menuPath"></nav>
Here is my app and routing set up
var rxApp = angular.module('ehrxApp', ['ngRoute']);
// configure our routes
rxApp.config(function ($routeProvider) {
$routeProvider
.when('/', {
controller: 'mainController',
templateUrl: '/content/views/index.html'
})
.when('/census', {
templateUrl: '/content/views/admission/census.html',
controller: 'censusController'
})
.when('/messages', {
templateUrl: '/content/views/account/messages.html',
controller: 'messagesController'
})
.when('/profile', {
templateUrl: '/content/views/account/profile.html',
controller: 'profileController'
})
});
In my main controller I set the menuPath value here:
rxApp.controller('mainController', function (userService, $scope, $http) {
evaluate_size();
$scope.menuPath = "/content/views/index.menu.html";
});
rxApp.controller('censusController', function ($scope, $http, $sce, censusService) {
$scope.menuPath = "/content/views/admission/census.menu.html";
evaluate_size();
});
When the page switches to the census view it should change the menu. What happens though is the first page loads the main menu, then no matter what other page you go to the menu never updates.
I imagine this problem has something to do with a primitive values and prototypical inheritance between child scopes, but would need to see more of your html to determine that. Without that, I propose an alternative way that may solve your problem and keep the config all in one place.
$routeProvider will accept variables and keep them on the route, even if angular doesn't use them. so we modify your routing by including the menuPath like so:
var rxApp = angular.module('ehrxApp', ['ngRoute']);
// configure our routes
rxApp.config(function ($routeProvider) {
$routeProvider
.when('/', {
controller: 'mainController',
templateUrl: '/content/views/index.html',
menuPath: '/content/views/index.menu.html'
})
.when('/census', {
templateUrl: '/content/views/admission/census.html',
controller: 'censusController',
menuPath: '/content/views/admission/census.menu.html'
})
.when('/messages', {
templateUrl: '/content/views/account/messages.html',
controller: 'messagesController'
})
.when('/profile', {
templateUrl: '/content/views/account/profile.html',
controller: 'profileController'
})
});
Remove setting $scope.menuPath from each controller, then finally add a watch on rootScope that will change the menuPath on $routeChangeSuccess
rxApp.run(['$rootScope', function ($rootScope) {
$rootScope.$on('$routeChangeSuccess', function(event, current) {
if (current && current.$$route && current.$$route.menuPath) {
$rootScope.menuPath = current.$$route.menuPath;
} else {
$rootScope.menuPath = '';
}
});
}]);

Resources