How to get the current route's controller (or scope)? - angularjs

I have a controller that needs a thing provided by a route resolve function:
$routeProvider.when('/some/url', {
controller: MyController,
controllerAs: 'myCtrl',
resolve: {
theAnswer: ['deepThought', function(deepThought) {
return deepThought.computeTheAnswerAndReturnAPromise();
}]
}
});
var MyController = ['$route', function($route) {
this.theAnswer = $route.current.theAnswer;
}];
Now I want to do an end-to-end test, checking that the route matches and that parameters are propagated properly:
// ...set up the routes...
$location.path('/some/url');
$rootScope.$digest();
var ctrl = ???;
expect(ctrl.aThing).toBe(42);
In the non-test setup, I can put in a log statement and see that the controller is being created successfully and gets the correct data injected. The only problem is: how to get hold of the controller in the test?
There is $route.current.controller, but it contains the controller's constructor function and not the controller instance.
The documentation promises a $route.current.locals.$scope, from which I could get myCtrl, but the $scope property doesn't actually exist unless we also use ngView (it gets set here).
The controller isn't registered with any module, so I can't use $provide to intercept its creation and stash the controller somewhere.

Found it, thanks to #PSL's comment. The thing that actually constructs the controller is the ngView link function. We can fake that easily enough:
var ctrl = $controller(MyController, $route.current.locals);

Related

How do I put a variable in $scope in ALL my controllers

Let's say I have a variable flag called is_logged_in, I want it to be in scope in all my controllers. So that if I have {{is_logged_in}} on every page in my app, it will print it out.
How do I achieve this without writing duplicate code like this, in all my controllers:
function MyCtrl($scope, IsLoggedInService) {
$scope.is_logged_in = IsLoggedInService.IsLoggedIn();
}
Your best bet is to use the $rootScope. This, as the name implies, correspond to the root scope of your application and is therefore potentially available (via DI) in any of your controllers. All you need to do is add $rootScope as a DI dependency in each of your controllers that requires it:
function MyCtrl($scope, $rootScope {
$rootScope...
}
In your templates, the $rootScope always available by referencing $root in an angular expression.
You would do something like this:
<p>{{$root.is_logged_in}}</p>
Change to this:
$rootScope.is_logged_in = IsLoggedInService.IsLoggedIn();
if you want to check whether the user is logged in or not
i think the right approach to your problem is to use resolve property in the route, so the user can't navigate to certain pages if he isn't logged in and once he logged in you can inject the user object to the controller
for example to navigate to home page you must be logged in
.when("/home", {
templateUrl: "homeView.html",
controller: "homeController",
resolve: {
user: function(AuthenticationService){
return AuthenticationService.getUser();
}
}
})
app.controller("homeController", function ($scope, user) {
$scope.user = user;
});
https://www.sitepoint.com/implementing-authentication-angular-applications/
and if you just want a global variable you can use $rootScope
Another approach, yet using the $rootScope, is to use $broadcast to create an observer for that variable.
In order to do this, you should broadcast an event when this variable is changed, like this:
$rootScope.$broadcast('user_logged_in');
And then, watch it using the $on method. Here:
$scope.$on('user_logged_in', function(event, args) {
// here you do what you want, like:
$scope.logged_in = true;
});
If you want to know more about it, angular also provides the $emmit method, that is used when you want that scopes above yours listen to that event. ( you can find more here : $rootScope.$broadcast vs. $scope.$emit
Yet, you should read more about in the docs, What are scopes? and here: $rootScope.Scope

Angular Ui-router Resolve concept

I was reading the docs of ui-router but I couldn't grasp the concept of resolves for controllers in each state. I am not able to figure out where should we use resolve and why the controller attached to a state is not enough (as we can inject any dependencies in it we want) ?
I've tried going through docs and other tutorials several times but its quite confusing , Can someone please explain it with its real life application?
Imagine you want to create a modal and pass some data to it. I'm using the angular-ui-bootstrap modals for this example.
var openExampleModal = function () {
var modalInstance = $modal.open({
templateUrl: "Modal.html",
controller: "ModalController",
size: "lg"
});
return modalInstance.result;
};
Now if you want to pass some data to this modal on initialization, you can either save it in your $rootScope or some data service, or you can use resolve to inject it into your controller directly without having to use anything else.
var openExampleModal = function (myData) {
var modalInstance = $modal.open({
templateUrl: "Modal.html",
controller: "ModalController",
size: "lg",
resolve: {
sampleData: function () {
return myData;
}
}
});
return modalInstance.result;
};
and in your controller you would have:
MyController.$inject = ["sampleData"];
function Mycontroller(sampleData) {
//You can access the data you passed on via sampleData variable now.
};
Resolve is used to inject your own custom objects into the controller, not for injecting dependencies.
A resolve is simply a value that is passed to the controller upon instantiation (which are used like an injected value). The neat thing about them is that if the value returned is a promise, the view/controller won't load until the promise has resolved.
The way you use them is by adding a resolve key to your route state, and returning the object you want injected into your controller (also naming it). For example:
.state('example', {
url: '/page',
templateUrl: 'sometemplate.html',
controller: 'SomeCtrl',
resolve: {
injectionName: function(){
// return a value or promise here to be injected as injectionName into your controller
}
}
});
Then inside your controller you simply add the resolve name to the controller injected values:
.controller('SomeCtrl', function($scope, injectionName){
// do stuff with injectionName
});
Just note that if you do return a promise, the value that is injected is the result of the promise (not the promise itself). Also note that if the promise errors the view/controller will not load, and an error will be thrown. As #koox00 commented, this error will fail silently unless $stateChangeErrorError is handled (usually in your apps primary run() function).
So why would you use this? Well if not inferred from above, you do this usually when you want your view/controller to wait until some async process has completed before loading a particular state. This saves you from creating loaders or loading processes for every single view/controller, moving it to a simple definition of what needs to be loaded.
As said by Jean-Philippe you can use resolve if you want to load some data before switching to a certain state. Resolve waits and blocks until the data is arrived and only then the state transition is done.
It is an highly discussed topic whether using a resolve or loading the data on the fly within the controller. I would say: It depends on your use case :)
Further info from supercool todd motto: https://toddmotto.com/resolve-promises-in-angular-routes/

When using ngRoute, are controllers duplicated?

I'm using ngRoute, with the following configuration :
myApp.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/view1', {
controller:'my1Ctrl',
templateUrl:'views/view1.html'
})
.when('/view2', {
controller:'my2Ctrl',
templateUrl:'views/view2.html'
});
}])
For the purpose of this example, I'm logging the ID of the controller every second. So, in the my1Ctrl controller, I add the following code :
$scope.f = function(){
console.log('Test Controller, id: ', $scope.$id);
setTimeout($scope.f, 1000);
};
setTimeout($scope.f, 1000);
Finally, I launch my app and navigate 3 times from view1 to view2. After that, every second, I get the following log:
Test Controller, id: 00A
Test Controller, id: 00I
Test Controller, id: 00E
If my test case is not relevant, please tell me.
My question: When ngRoute instanciates a new controller, is the old one removed or is it still in memory? If it is, can I configure ngRoute to re-use the same controller or to distroy the old one ?
$scope.$id is not the id of the controller but of the scope instead.
When you open new page defined with $routeProvider AngularJS "instantiates" new controller (i.e. calls the internal method instantiate). This method invokes the controller's function with new so it creates new object. But it's not all AngularJS does. Before calling the controller's constructor with new, AngularJS resolves all it's dependencies. If the controller has local dependency called $scope AngularJS creates new $scope, each scope has unique identifier - $scope.$id.
Of course, in order to prevent memory leaks AngularJS does not keep old controllers in the memory, so you shouldn't worry about this.

$routeParams is empty in main controller

I have this piece of layout html:
<body ng-controller="MainController">
<div id="terminal"></div>
<div ng-view></div>
<!-- including scripts -->
</body>
Now apparently, when I try to use $routeParams in MainController, it's always empty. It's important to note that MainController is supposed to be in effect in every possible route; therefore I'm not defining it in my app.js. I mean, I'm not defining it here:
$routeProvider.when("/view1", {
templateUrl: "partials/partial1.html"
controller: "MyCtrl1"
})
$routeProvider.when("/view2", {
templateUrl: "partials/partial2.html"
controller: "MyCtrl2"
})
// I'm not defining MainController here!!
In fact, I think my problem is perfectly the same as this one: https://groups.google.com/forum/#!topic/angular/ib2wHQozeNE
However, I still don't get how to get route parameters in my main controller...
EDIT:
What I meant was that I'm not associating my MainController with any specific route. It's defined; and it's the parent controller of all other controllers. What I'm trying to know is that when you go to a URL like /whatever, which is matched by a route like /:whatever, why is it that only the sub-controller is able to access the route parameter, whereas the main controller is not? How do I get the :whatever route parameter in my main controller?
The $routeParams service is populated asynchronously. This means it will typically appear empty when first used in a controller.
To be notified when $routeParams has been populated, subscribe to the $routeChangeSuccess event on the $scope. (If you're in a component that doesn't have access to a child $scope, e.g., a service or a factory, you can inject and use $rootScope instead.)
module.controller('FooCtrl', function($scope, $routeParams) {
$scope.$on('$routeChangeSuccess', function() {
// $routeParams should be populated here
});
);
Controllers used by a route, or within a template included by a route, will have immediate access to the fully-populated $routeParams because ng-view waits for the $routeChangeSuccess event before continuing. (It has to wait, since it needs the route information in order to decide which template/controller to even load.)
If you know your controller will be used inside of ng-view, you won't need to wait for the routing event. If you know your controller will not, you will. If you're not sure, you'll have to explicitly allow for both possibilities. Subscribing to $routeChangeSuccess will not be enough; you will only see the event if $routeParams wasn't already populated:
module.controller('FooCtrl', function($scope, $routeParams) {
// $routeParams will already be populated
// here if this controller is used within ng-view
$scope.$on('$routeChangeSuccess', function() {
// $routeParams will be populated here if
// this controller is used outside ng-view
});
);
As an alternate to the $timeout that plong0 mentioned...
You can also inject the $route service which will show your params immediately.
angular.module('MyModule')
.controller('MainCtrl', function ($scope, $route) {
console.log('routeParams:'+JSON.stringify($route.current.params));
});
I have the same problem.
What I discovered is that, $routeParams take some time to load in the Main Controller, it probably initiate the Main Controller first and then set $routeParams at the Child Controller. I did a workaround for it creating a method in the Main Controller $scope and pass $routeParams through it in the Child Controllers:
angular.module('MyModule')
.controller('MainController', ["$scope", function ($scope) {
$scope.parentMethod = function($routeParams) {
//do stuff
}
}]);
angular.module('MyModule')
.controller('MyCtrl1', ["$scope", function ($scope) {
$scope.parentMethod($routeParams);
}]);
angular.module('MyModule')
.controller('MyCtrl2', ["$scope", function ($scope) {
$scope.parentMethod($routeParams);
}]);
had the same problem, and building off what Andre mentioned in his answer about $routeParams taking a moment to load in the main controller, I just put it in a timeout inside my MainCtrl.
angular.module('MyModule')
.controller('MainCtrl', function ($scope, $routeParams, $timeout) {
$timeout(function(){
// do stuff with $routeParams
console.log('routeParams:'+JSON.stringify($routeParams));
}, 20);
});
20ms delay to use $routeParams is not even noticeable, and less than that seems to have inconsistent results.
More specifically about my problem, I was confused because I had the exact same setup working with a different project structure (yo cg-angular) and when I rebuilt my project (yo angular-fullstack) I started experiencing the problem.
You have at least two problems here:
with $routeParams you get the route parameters, which you didn't define
the file where you define a main controller doesn't really matter. the important thing is in which module/function
The parameters have to be defined with the $routeProvider with the syntax :paramName:
$routeProvider.when("/view2/name1/:a/name2/:b"
and then you can retrieve them with $routeParams.paramName.
You can also use the query parameters, like index.html?k1=v1&k2=v2.
app.js is the file where you'd normally define dependencies and configuration (that's why you'd have there the app module .config block) and it contains the application module:
var myapp = angular.module(...);
This module can have other modules as dependencies, like directives or services, or a module per feature.
A simple approach is to have a module to encapsulate controllers. An approach closer to your original code is putting at least one controller in the main module:
myapp.controller('MainCtrl', function ($scope) {...}
Maybe you defined the controller as a global function? function MainCtrl() {...}? This pollutes the global namespace. avoid it.
Defining your controller in the main module will not make it "to take effect in all routes". This has to be defined with $routeProvider or make the controller of each route "inherit" from the main controller. This way, the controller of each route is instantiated after the route has changed, whereas the main controller is instantiated only once, when the line ng-controller="MainCtrl" is reached (which happens only once, during application startup)
You can simply pass values of $routeParams defined into your controller into the $rootScope
.controller('MainCtrl', function ($scope, $routeParams, MainFactory, $rootScope) {
$scope.contents = MainFactory.getThing($routeParams.id);
$rootScope.total = MainFactory.getMax(); // Send total to the rootScope
}
and inject $rootScope in your IndexCtrl (related to the index.html)
.controller('IndexCtrl', function($scope, $rootScope){
// Some code
});

Pass data to angular's nested controller

The problem
I'm using UI Bootstrap's dialog service in my application, this service creates modal dialog and I do that using the following method on my outer $scope:
$scope.showRouteEditDialog = function (template, route) {
// argument `route` is not currently used
var dialog = $dialog.dialog({
backdrop: true,
keyboard: false,
backdropClick: true,
templateUrl: template,
controller: 'RouteController'
});
dialog.open().then(function(result) {
alert(result); // This line is called when dialog is closed
});
}
This method is later called from partial view with the following markup
<i class="halflings-icon edit"></i>
My dialog handles editing of a route (route is a sub-model within main model) and therefore I would like to pass that route to the dialog so that it treats it like it's own model without knowing anything about the outer model.
My initial guess on this problem was to assign the route argument to dialog variable, something like dialog.route = route and have it later used within controller with the following code:
Application.controller('RouteController', ['$scope', 'dialog', function ($scope, dialog) {
// `dialog` is our dialog and it is injected with injector
doSomethingWith(dialog.route)
}]);
Though this approach creates a dependency and doesn't look like an angular's way of doing things
I have also found this post saying that I should be using service for that purpose, but it seems like this solution is an overkill for such minor problem.
Question
What is the angular way of passing a value from outer controller to an inner one with scenario described above.
Thank you
You can use "resolve" -
var dialog = $dialog.dialog({
resolve: {route: function(){return "route"}}
});
and later you can inject the "route" value inside of your controller
.controller("SomeCtrl",function(route){
})

Resources