I have an AngularJS single-page app displaying 3 views (which are actually 3 directives). To illustrate my question, let's assume my UI is identical to that of GMail and that my 3 views are:
These 3 views need to update themselves whenever the path changes. For example:
What's the best way to do this in AngularJS?
So far, I have:
$routeProvider
only supports one ngView
.This kind of works, but I have several issues:
My code to watch for path changes (I put this in a service or in a controller):
var watchExpression = function() { return $location.path(); };
var listener = function(newPath, oldPath) {
// Broadcast event on $rootScope
$rootScope.$broadcast('PathChanged', newPath);
};
$rootScope.$watch(watchExpression, listener);
Then, in a view controller, I catch the event:
$scope.$on('PathChanged', function(event, path) {
// Update view based on new path.
});
Any help appreciated. Thanks.
The $location in AngularJS basically uses a window. location service. The $location is used to read or change the URL in the browser and it is used to reflect that URL on our page. Any change made in the URL is stored in the $location service in AngularJS.
$broadcast in AngularJS? The $rootScope. $broadcast is used to broadcast a “global” event that can be caught by any listener of that particular scope. The descendant scopes can catch and handle this event by using $scope.
The difference between $broadcast() and $emit() is that the $broadcast() sends the event from the current controller to all of its child controllers. The $emit() method sends an event from current controller to all of its parent controllers.
$routeUpdate. Broadcasted if the same instance of a route (including template, controller instance, resolved dependencies, etc.) is being reused. This can happen if either reloadOnSearch or reloadOnUrl has been set to false .
Your final version seems fine with the locationChangeSuccess, but for others reading this, I think you ruled out the $routeProvider too quickly. You can have one ng-view for the main content pane that changes with the path, and then other independent ("static") controllers/templates for the navigation pane and toolbar.
Now to listen to route changes in these other 2 controllers:
$rootScope.$on('$routeChangeSuccess', function(evt, cur, prev) {
...do what you have to do here, maybe set a $rootScope.path as you did
})
All using native Angular functionality. I actually do this in http://provok.in, a website I built using Angular, and I have a similar layout (well, not exactly, but I have "static" sections and an ng-view for the main content, dynamically updated based on the path, by the routeProvider).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With