Skip to content Skip to sidebar Skip to footer

AngularJS $location Without Templates

I would like to use the $locationProvider service in AngularJS without rendering a new HTML template in my ng-view. I have a div element that is shown on demand via ng-show binding

Solution 1:

Use the source, Luke :-) http://code.angularjs.org/1.0.0/angular-1.0.0.js

If you look at the ngViewDirective (which is actually super simple), it just catches the '$routeChangeSuccess' event and changes view accordingly.

So you could catch $routeChangeSuccess and then inject $route into your controller, check if the new route is the one you want, and show accordingly. (I think :D)

This might work (untested):

//declare a route so angular knows to broadcast about it when it's hit
//We aren't declaring any actions for the route though,
//since below we define custom actions
myApp.config(function($routeProvider) {
  $routeProvider.when('/superman', {});
}); 

function SupermanCtrl($scope, $route) {
  $scope.$on('$routeChangeSuccess', function() {
    //If this doesn't work, console.log $route.current to see how it's formatted
    if ($route.current == '/superman')
      $scope.show = true;
    else
      $scope.show = false;
  });
}

I hope it works, and if it doesn't it should be enough to start with. I encourage you to read the ngViewDirective, and if this doesn't work search for '$routeChangeSuccess' and figure out how/why it gets broadcasted.


Post a Comment for "AngularJS $location Without Templates"