AngularJS $位置而不模板 [英] AngularJS $location without templates

查看:154
本文介绍了AngularJS $位置而不模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用AngularJS的 $ locationProvider 服务而不在我的 NG-视图呈现一个新的HTML模板

I would like to use the $locationProvider service in AngularJS without rendering a new HTML template in my ng-view.

我有一个 DIV 元素通过 NG-展示显示在需求绑定到数据的存在元件。我想连线这通过 $ locationProvider 浏览器的位置,但保持相同的模板中。

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.

模板:

<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
  }
}

我无法弄清楚如何将 $位置服务于这个集成。 AngularJS也覆盖如果它被设置为 history.pushState 位置直接。

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.

推荐答案

使用源,卢克:-) <一个href=\"http://$c$c.angularjs.org/1.0.0/angular-1.0.0.js\">http://$c$c.angularjs.org/1.0.0/angular-1.0.0.js

如果你看一下ngViewDirective(这实际上是超级简单),它只是抓住了'$ routeChangeSuccess事件和变化据此来。

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

所以,你可以赶上$ routeChangeSuccess然后注入$路由到控制器,检查新的路线是你想要的,并相应地显示出来。 (我认为:D)

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

我希望它的作品,如果它不应该是足够的开始。我建议你​​阅读ngViewDirective,如果这也不行搜索'$ routeChangeSuccess,并找出如何/为什么它被播出。

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.

这篇关于AngularJS $位置而不模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆