Is it possible to init a scope and ng-view in load?
Problem:
I have an AngularJS App with a list of Resellers. You can choose a reseller on a map and open details in a overlay-div (calling it with ng-show="show") on the route
when(
'/dealer/:id', {
templateUrl: 'files/tpl/dealer-details.html?19',
controller: 'DealerDetailsCtrl',
activetab: 'details'}
).
The client wants now that when a customer opens the page, an initial details-overlay is open with the details.
Solution (possible):
Is it possible to, maybe ng-init, send the hardcoded :id of the chosen reseller to the controller and trigger the detail-overlay, so that it opens on load? Or maybe to trigger the route with the ID.
If I understand you correctly, you want a default value for :id if not provided?
Best option is to have two when clauses in your $routeProvider:
$routeProvider.when(
'/dealer', {
templateUrl: 'files/tpl/dealer-details.html?19',
controller: 'DealerDetailsCtrl',
activetab: 'details'}
);
$routeProvider.when(
'/dealer/:id', {
templateUrl: 'files/tpl/dealer-details.html?19',
controller: 'DealerDetailsCtrl',
activetab: 'details'}
);
In your controller you can then assign a default value if not defined:
$scope.dealer = $routeParams.id || 'defaultDealerId';
Related
(function(app) {
app.config(function($stateProvider, $httpProvider, $urlRouterProvider) {
//region Registering States
$urlRouterProvider.otherwise('/home');
var dashboard = {
name: 'home',
url: '/home',
templateUrl: 'home.html',
controller: 'homeCtrl'
};
var home = {
name: 'profile',
url: '/profile',
templateUrl: 'profile.html',
controller: 'profileCtrl'
};
$stateProvider.state(dashboard);
$stateProvider.state(home);
//endregion
});
app.controller('homeCtrl', ['$rootScope','$scope', function($rootScope,$scope) {
$rootScope.pageTitle = "home";
$scope.callEvent = function(){
$rootScope.$broadcast('newEvent',"data");
}
}]);
console.log('called');
}(angular.module('app', ['ui.router'])));
2'nd controller:
(function(app) {
app.controller('profileCtrl', ['$rootScope','$scope', function($rootScope,$scope) {
$rootScope.pageTitle = "profile";
$rootScope.$on('newEvent',function(ev,data){
alert('Event fired from home');
});
$scope.$on('newEvent',function(ev,data){
alert('Event fired from home');
});
}]);
}(angular.module('app')));
App with 2 controller:
1 controller: fired a event using $broadcast
2 controller: capturing event fired from 1'st controller.
But unable to accomplish that.
NOTE: If html page load once( 2'nd controller), $on event is fired else it's doesn't listen to any event.
For better understanding i had created a plunkr
Please first review the code
#vojta
Thanks
The problem is you are loading the controllers via states. This means they only initialize once the state becomes active (i.e you navigate to the html).
If you add a console log to profileCtrl you see that it does not get fired until the page is active.
Angular doesn't load the controller if it wasn't called.
Think of it as a singleton object which won't init until you will try to run it.
In your case, you set a controller for a specific route which means it will run only after you go to its route address.
What you actually will want to do is to have some directive Angular Directive
That will control on your menu bar that you will load on the main page and maybe every other page.
And for the home page, you should have a different controller that will be active only when the user is on the page.
As a side note, don't assume the "home" controller will be available once you leave the home page (Angular destroy).
Pretty new to Angular, I am sure I'm missing something obvious here. I am using ui-router.
I want to provide a link to my clients so that they can click the URL link and visit the web app with the appropriate partial. I also want to be able to pass in parameters. Here's how I approached this (kind of hokey). This is in my main controller:
var pNumber = $location.search().number;
if (!(pNumber == null || pNumber == "")){
$state.go('view-ticket');
}
Here is my app.js:
$stateProvider
.state('home', {
url: "/",
templateUrl: 'partials/welcome-screen.html',
controller: 'mainPageController'
})
.state('submit-ticket', {
url: "/submit-ticket",
templateUrl: 'partials/ticket-submit.html',
controller: 'TicketSystemTestCtrl'
})
.state('view-ticket', {
url: "/view",
templateUrl: "partials/ticket-central.html",
controller: 'TicketCentralCtrl'
})
The logic is this: If the URL contains a param 'number' inject ticket-central.html partial.
However, when I run this in the debugger, it seems the first part of the code got executed before it loads the welcome-screen.html partial. How to solve this?
EDIT: I am trying to type this into the URL: http://localhost/techsupport/view and I want it to load the ticket-central.html partial into the main view. However, it won't work.
if i understand correctly all you want to do is to provide a possibility to 'deep-link' to the 'view-ticket' state.
for this search params are not the ideal solution as they are optional, just use path variables:
.state('view-ticket', {
url: '/view/:ticketNumber,
template: 'partials/ticket-central.html',
controler: 'TicketCentralCtrl'
})
also don't use the $location service if you don't really have to, have a look at $stateParams
here is a small plunkr with a welcome and a ticket state
launch the preview in a separate window to see how the url changes - you can also refresh on each page and the correct state will be loaded
https://plnkr.co/edit/r3UcYbfwET0OVwkd77Rv
I'm using the native AngularJS router and was wondering if there is a way to assign a controller to a route conditionally. For example, let's say I have three user types:
Guest
User
System Admin
When they come to the home page, I want to be able assign a different controller based on the user type. So I would have three registered controllers: guestHomeCtrl, userHomeCtrl, systemAdminHomeCtrl.
I imagined something like this:
$routeProvider
.when( '/' , {
controller: getHomeCtrl(),
controllerAs: 'homeCtrl'
})
I know I can just pass in the string of the registered controller, but the main issue is being able to find out what type of user is logged in. I have a userService that typically keeps track of that, but it doesn't seem like I can access it from where I set up the routes. Or am I mistaken?
Any direction would help out a lot.
I would suggest using userService with a single controller. Read through the page below, specifically the resolve argument.
https://docs.angularjs.org/api/ngRoute/provider/$routeProvider
This blog post also describes how to use the resolve.
http://odetocode.com/blogs/scott/archive/2014/05/20/using-resolve-in-angularjs-routes.aspx
Try sending the specific function or variable you need to the controller. I used userService.User.userAccountStatus, but it really depends on the setup in your service file.
$routeProvider
.when( '/' , {
controller: HomeCtrl,
controllerAs: 'HomeCtrl',
resolve: {
userService: function(userService) {
return userService.User.userAccountStatus();
}
}
})
I use ngInject for injecting dependencies, but I assume you get the gist of giving services to a controller.
angular
.module('app')
.controller('HomeCtrl', HomeCtrl)
/** #ngInject */
function HomeCtrl($scope, $log, $state, userService) {
}
I can provide further examples if you need them.
I have two Angularjs broadcast options one is for add and other one is for edit for both routing i have different keys to redirect user to the page. For add state $stateParams processId is rendered but for edit state ChallengeKey id is undefined. So question is how to defined optional parameters with router so if its edit it can take challengeKey and route it to appropriate page.
so far tried code..
Ctrl.js
$scope.$on('addProcessChallenge', function (s,processId){
$location.path('/addEditChallenge/' + processId);
}
$scope.$on('editPrcChallenge', function (s,chalengeKey){
$location.path('/addEditChallenge/' + chalengeKey);
}
app.js
.state('app.addChallenge', {
url: '/addChallenge/:processId:/challengeKey',
templateUrl: 'views/processChallenge.html',
controller: 'Ctrl',
data: {
authenticate: true
},
angular.module('Stations', ['ngRoute'])
.config(function ($routeProvider) {
$routeProvider
.when('/documents/:stationId', {
templateUrl: '/Scripts/Modules/checklist/views/index.html',
controller: 'checklistController'
})
.when('/documents/details', {
templateUrl: '/Scripts/Modules/checklist/views/details.html',
controller: 'checklistDetailsController'
})
});
Now if i type the url /stations#/documents/4, it jumbs to to the documents view and show all the documents in that station. But if i go to the url stations#/documents/details?Id=3&type=note, it still go to the documents main view and not the details view.
Could you please give me a hint on what i'm doing wrong?
Here the router beleives that details is a :stationId
So it matches the first route /documents/:stationId and affects the value details to the stationIdparameter.
You should change the route for the details page to
.when('/details', {
Or if you want to say that stationId must be a number, you can do that with angular ui-router :
https://github.com/angular-ui/ui-router/wiki/URL-Routing#regex-parameters
Probably you should change the route to
.when('/documents/details/:id/:note', {... });
This would be useful to get the params using $routeParams in your controller etc.
Because first route matched is executed and details in that URL is considered as stationId.
Put second route first so that it is matched first. Like this.
angular.module('Stations', ['ngRoute']).config(function ($routeProvider) {
$routeProvider
.when('/documents/details', {
templateUrl: '/Scripts/Modules/checklist/views/details.html',
controller: 'checklistDetailsController'
})
.when('/documents/:stationId', {
templateUrl: '/Scripts/Modules/checklist/views/index.html',
controller: 'checklistController'
})
});
But this will mean, if your stationId by any chance is the word 'details', then it will be matched to first route and not to the second route. So consider avoiding this type of configuration.
You need to put in the params in the route:
.when('/documents/details:documentId', {
templateUrl: '/Scripts/Modules/checklist/views/details.html',
controller: 'checklistDetailsController'
});
See: https://docs.angularjs.org/api/ngRoute/service/$route