AngularJS $location without templates

╄→尐↘猪︶ㄣ 提交于 2020-01-04 03:07:04

问题


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 to the existence of a data element. I would like to wire this to the browser location via the $locationProvider but stay within the same template.

Template:

<div> other stuff ... </div>

<div ng-show="model">{{ model.element }}</div>

Controller:

Controller = function($scope, $location) {
  $scope.show = function() {
    $scope.model = model;    // show div
  }

  $scope.hide = function() {
    $scope.model = null;    // hide div
  }
}

I can't figure out how to integrate the $location service in this. AngularJS also overwrites the location if it is set with history.pushState directly.


回答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.



来源:https://stackoverflow.com/questions/11179528/angularjs-location-without-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!