How to call a function in AngularJs when route matches? - angularjs

$routeProvider.when('/ticket', {
controller: TicketController,
templateUrl: Routing.generate('ticket_list')
});
displays a simple list where each entry is selectable. However on select no extra view is loaded. Every thing is in ticket_lost template. The template has some hidden fields that are revealed when entry is clicked.
I can define which entry is selected internally by setting
selectedTicket = 1;
So when there is a route like
/ticket/1
I want to call a function that sets selectedTicket to 1. Is that possible? How to do that? What do I have to change in routing?

Take a look at $routeParams service.
It allows to set up route with parameters which will be parsed by service:
// Given:
// URL: http://server.com/index.html#/ticket/1
// Route: /ticket/:ticketId
//
// Then
$routeParams ==> {ticketId:1}
In your controller:
angular.module('myApp')
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/ticket', {controller: 'TicketController'});
$routeProvider.when('/ticket/:ticketId', {controller: 'TicketController'});
$routeProvider.otherwise({redirectTo: '/ticket'});
}])
.controller('TicketController', function ($scope, $routeParams) {
var init = function () {
if ($routeParams.ticketId) {
$scope.ticketSelected($routeParams.ticketId);
}
};
// fire on controller loaded
init();
});

Related

Call Ionic function from the state views options

I have a controller 'ProjectController' which has various CRUD functions inside.
I want to be able to call my API when loading a view and without having to create another controller.
Pseudo code:
.state('app.my-project', {
url: '/projects/my-projects',
views: {
'menuContent': {
templateUrl: 'templates/my_projects.html',
function: myProject()
}
}
});
And in my controller:
.controller('ProjectCtrl', function($scope, $state, $auth, $http, $ionicPopup, $rootScope) {
$scope.myProjects = function() {
// foo
}
});
So the goal is that when setting up the states, I can call a function instead of just going to a controller?
The example im using is that when setting up the state for "my projects" I can call a function from within the controller.
Instead of having to create individual controllers for each action.

How to pass routeProvider attributes to controller

I need to setup a controller with some data passed from the routeProvider.
I would like the value topic to be passed to my controller VideoCtrl and then assigned to a value such as video.topic
$routeProvider
.when('/video/:topic', {
templateUrl: 'pages/video/video-page.tmpl.html',
controller: 'VideoCtrl',
controllerAs: 'video'
});
It seems like I should just need to call $routeProvider in my controller function:
app.controller('VideoCtrl', function($routeProvider) {
var video = this;
video.topic = $routeProvider.topic; // What do I need to add here?
...
});
But I can't seem to figure out how to inject $routeProvider into the controller.
I think, you need to pass the $routeParams as controller parameter and then you will able to get the passed route value.
app.controller('VideoCtrl', function($routeParams) {
var video = this;
video.topic = $routeParams.topic;
...
});

How to change templateURL for angular UI router based on customer settings

I have multiple clients on my angular app and I want to create different themes inside angular (only the visual part will change, controllers remain the same.
I have a "security" module which manages the authentication, currentLoggedIn user and so on.
var security = angular.module('security', ['ui.router'])
// .factory('authService', authService);
.service('authService', ['$http', '$q', '$window', 'CONSTANTS', '$location', 'currentUser', '$state', '$rootScope', authService])
.factory('authCheck', ['$rootScope', '$state', 'authService', securityAuthorization])
and authService is basically having these methods/values
service.login = _login;
service.logout = _logout;
service.reset = _reset;
service.isAuthenticated = _isAuthenticated;
service.requestCurrentUser = _requestCurrentUser;
service.returnCurrentUser = _returnCurrentUser;
service.hasRoleAccess = _hasRoleAccess;
How can I get access to currentUser inside templateURL function to modify the URL based on data for currentUser?
AuthService and AuthCheck are empty when accessed in templateURL function.
$stateProvider
.state('home', {
url: '/home',
templateUrl: function(authService, authCheck) {
console.log (authService, authCheck);
return 'components/home/home.html'
},
data: {
roles: ['Admin']
},
resolve: {
"authorize": ['authCheck', function(authCheck) {
return authCheck.authorize();
}],
"loadedData": ['metricsFactory', 'campaignFactory', '$q', '$rootScope', 'selectedDates', loadHomeController]
},
controller: 'HomeController',
controllerAs: 'home'
});
In case, we want to do some "magic" before returning the template... we should use templateProvider. Check this Q & A:
Trying to Dynamically set a templateUrl in controller based on constant
Because template:... could be either string or function like this (check the doc:)
$stateProvider
template
html template as a string or a function that returns an html template
as a string which should be used by the uiView directives. This
property takes precedence over templateUrl.
If template is a function, it will be called with the following
parameters:
{array.} - state parameters extracted from the current
$location.path() by applying the current state
template: function(params) {
return "<h1>generated template</h1>"; }
While with templateProvider we can get anything injected e.g. the great improvement in angular $templateRequest. Check this answer and its plunker
templateProvider: function(CONFIG, $templateRequest) {
console.log('in templateUrl ' + CONFIG.codeCampType);
var templateName = 'index5templateB.html';
if (CONFIG.codeCampType === "svcc") {
templateName = 'index5templateA.html';
}
return $templateRequest(templateName);
},
From the documentation:
templateUrl (optional)
path or function that returns a path to an html template that should be used by uiView.
If templateUrl is a function, it will be called with the following parameters:
{array.<object>} - state parameters extracted from the current $location.path() by applying the current state
So, clearly, you can't inject services to the templateUrl function.
But right after, the documentation also says:
templateProvider (optional)
function
Provider function that returns HTML content string.
templateProvider:
function(MyTemplateService, params) {
return MyTemplateService.getTemplate(params.pageId);
}
Which allows doing what you want.

Why controller doesn't respond on route update?

I would like preserve instance of controller without reloading. I set reloadOnSearch to false and I manage route change in my controller. Here is the code.
This is example of my link next. I have defined following module.
angular.module('app.products', ['ngRoute', 'ngResource'])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/:section/:view/:number', {
templateUrl: 'tpl/table.html',
controller: 'ProductsCtrl',
controllerAs: 'productsCtrl',
reloadOnSearch: false
});
}])
.controller('ProductsCtrl', ['$scope', '$routeParams', '$location', ProductsCtrl]);
Controller
function ProductsCtrl($scope, $routeParams, $location) {
$scope.$on('$routeUpdate', function () {
console.log("routeUpdate");
});
}
But the controller doesn't respond on changed route and text is not written to console output.
In the angular jargon, "search" refers only to the query string parameters part of the URL. For instance: ?key=value&page=42
And the "path" refers to the URL without that query string. Here /products/page/2 is a path.
When setting reloadOnSearch: false you're telling angular not to reload the view and the associated controller when only the query string parameters changes.
So if the path changes, for instance you navigate from /products/page/2 to /products/page/3, then the view will still be reloaded. No $routeUpdate will be fired because there is no need for that. You'll get the new parameters from $routeParams when your controller initialization function is called again.
However if the path doesn't change, but only the query string parameters do change. For instance when you navigate from /products?page=2 to /products?page=3. Then the view will not be reloaded and a $routeUpdate will be broadcast.
So the solution here would be to define page as a query string parameter instead of a path parameter:
angular.module('app.products', ['ngRoute', 'ngResource'])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/:section', {
templateUrl: 'tpl/table.html',
controller: 'ProductsCtrl',
controllerAs: 'productsCtrl',
reloadOnSearch: false
});
}])
.controller('ProductsCtrl', ['$scope', '$routeParams', '$location', ProductsCtrl]);
Controller:
function ProductsCtrl($scope, $routeParams, $location) {
$scope.setupView = function setupView(section, page) {
// Setup you view here
// ...
};
$scope.$on('$routeUpdate', function () {
// This is called when only the query parameters change. E.g.: ?page=2
$scope.setupView($routeParams.section, $routeParams.page)
});
// This one is called when the the path changes and the view is reloaded.
$scope.setupView($routeParams.section, $routeParams.page)
}
Instead of $routeUpdate, try to use $routeChangeSuccess.
$scope.$on('$routeChangeSuccess', function (scope, next, current) {
console.log("Your text goes here.");
});
You can use next and current to check your previous and next route.
Hope it helps.

AngularJS Pre-served $params variables for a controller defined inside of a route

Is it possible to pass your own variables in a defined route in AngularJS?
The reason why I'm doing this is because I have to data representations of the same page (one is a filtered view in terms of the JSON data) and all I need to do is give a boolean flag to the $params array to let the controller function know that this page is either filtered or non-filtered.
Something like this:
var Ctrl = function($scope, $params) {
if($params.filtered) {
//make sure that the ID is there and use a different URL for the JSON data
}
else {
//use the URL for JSON data that fetches all the data
}
};
Ctrl.$inject = ['$scope', '$routeParams'];
angular.modlule('App', []).config(['$routeProvider', function($routes) {
$routes.when('/full/page',{
templateURL : 'page.html',
controller : Ctrl
});
$routes.when('/full/page/with/:id',{
templateURL : 'page.html',
controller : Ctrl,
params : {
filtered : true
}
});
}]);
According to $routeProvider documentation, the route parameter of $routeProvider.when() has property resolve:
An optional map of dependencies which should be injected into the controller.
Something like this should work:
function Ctrl($scope, isFiltered) {
if(isFiltered) {
//make sure that the ID is there and use a different URL for the JSON data
}
else {
//use the URL for JSON data that fetches all the data
}
}
Ctrl.$inject = ['$scope', 'isFiltered'];
angular.modlule('App', []).config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/full/page',{
templateURL: 'page.html',
controller: Ctrl
});
$routeProvider.when('/full/page/with/:id',{
templateURL: 'page.html',
controller: Ctrl,
resolve: {
isFiltered: function() { return true; }
}
});
}]);
AFAIK it is not currently possible to specify additional parameters for a route. Having said this your use case could be easily covered by testing if :id is defined as part of $routeParams.
The thing is that AngularJS will match your routes either on '/full/page' or '/full/page/with/:id' so just by testing $routeParams for id presence in your controller:
if ($routeParams.id)
you would know in which case your are.
The alternative is to use different controllers for different routes.
mething like this must be work for filter:
function caseFilterCtrl($scope, $routeParams, $http) {
$http.get('./data/myDatas.json').success( function(data){
var arr = new Array();
for(var i=0; i < data.length; i++){
if(data[i].filter == $routeParams.id){
arr.push(data[i]); }
}
$scope.filtered= arr;
});
}
caseFilterCtrl.$inject = ['$scope', '$routeParams', '$http']; //for minified bug issue
and the routage :
angular.module('myFilterApp', []).
config(['$routeProvider', function($routeProvider){
$routeProvider.when('/filter/:id', {templateUrl: './view/partial/filter.html', controller: caseFilterCtrl});
$routeProvider.otherwise({redirectTo: '/filter/01'});
}
]);
You can get sneak params directly through $route.current.$$route.
function Ctrl($scope, $route) {
var filtered = $route.current.$$route.params.filtered;
}
angular.modlule('App', []).config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/full/page/with/:id',{
templateURL: 'page.html',
controller: Ctrl,
params : {
filtered : true
}
});
}]);
Although it work, I'd still prefer a resolve solution. params (or any name of your choice) could be overwritten by angularjs in future releases.

Resources