【问题标题】:AngularJS $location without templatesAngularJS $location 没有模板
【发布时间】:2012-06-26 03:06:41
【问题描述】:

我想在 AngularJS 中使用 $locationProvider 服务,而不在我的 ng-view 中呈现新的 HTML 模板。

我有一个div 元素,它通过ng-show 绑定到数据元素的存在来按需显示。我想通过$locationProvider 将它连接到浏览器位置,但保持在同一个模板中。

模板:

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

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

控制器:

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

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

我不知道如何在其中集成$location 服务。如果直接用history.pushState 设置,AngularJS 也会覆盖位置。

【问题讨论】:

    标签: javascript browser-history angularjs


    【解决方案1】:

    使用来源,卢克 :-) http://code.angularjs.org/1.0.0/angular-1.0.0.js

    如果您查看 ngViewDirective(实际上非​​常简单),它只会捕获 '$routeChangeSuccess' 事件并相应地更改视图。

    因此您可以捕获 $routeChangeSuccess 然后将 $route 注入您的控制器,检查新路由是否是您想要的,并相应地显示。 (我认为:D)

    这可能有效(未经测试):

    //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;
      });
    }
    

    我希望它有效,如果没有,那么开始就足够了。我鼓励您阅读 ngViewDirective,如果这不起作用,请搜索“$routeChangeSuccess”并弄清楚它是如何/为什么被广播的。

    【讨论】:

    猜你喜欢
    • 2013-04-23
    • 1970-01-01
    • 2020-08-29
    • 2014-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-01
    • 1970-01-01
    相关资源
    最近更新 更多