【问题标题】:Can't access element in the same view using AngularJS无法使用AngularJS访问同一视图中的元素
【发布时间】:2015-07-04 23:07:51
【问题描述】:

所以总的来说,我想用 AngularJS 构建一个单页应用程序,并且我希望我的页面为公共用户和注册用户提供不同的内容,因此我将导航栏、内容和页脚部分放入不同的视图中。结构如下:

  • index.html
  • script.js
  • navbar.html
  • content.html
  • footer.html
  • uirouter.html

这是uirouter.html的代码

<div ng-include="home.navbar"></div>
<div ng-include="home.content"></div>
<div ng-include="home.footer"></div>

这是 script.js

的代码
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(function($routeProvider, $locationProvider) {
  $routeProvider
  .when('/', {
    controller: 'RouteCtrl',
    templateUrl: 'uirouter.html'
  });
});

myApp.controller('RouteCtrl', function($scope) {
  $scope.home = {
    "navbar": "navbar.html"
    "content": "content.html",
    "footer": "footer.html"
  } 
});

并将 ng-app、ng-controller 和 ng-view 放到 index.html

...
<body ng-app="myApp" ng-controller="RouteCtrl" id="home" data-spy="scroll" data-target=".navbar-collapse" data-offset="100">
  <div ng-view=""></div>
...

所有视图都加载得很好,但问题是当我单击导航栏上的链接时,例如应该引用视图上每个元素的“功能”和“定价”,它不起作用。 navbar.html 是这样的

<nav class="navbar navbar-default navbar-fixed-top" role="navigation"> 
  <div class="container">
    <div class="navbar-header">
      <a class="navbar-brand" href="#"> <img src="images/logo.png" alt="logo"></a> </div>
    <div class="collapse navbar-collapse navbar-ex1-collapse">
      <ul class="nav navbar-nav navbar-right">
        <li class="active"><a href="#home">Home</a></li>
        <li><a href="#features">Features</a></li>
        <li><a href="#pricing">Pricing</a></li>
      </ul>
      </li>
      </ul>
    </div>
  </div>
</nav>

所以“功能”和“定价”应该在 content.html

中引用这些元素
...
<div id="containerfeatures" class="container"> 
  <div class="row mainFeatures" id="features">
...
<div class="row PageHead" id="pricing">
...

页面被重定向而不是引用元素,这里是 url

http://localhost/app/#/pricing

认为应该提到这个..

http://localhost/app/#pricing

我还是 AngularJS 的新手,所以我还在到处徘徊。这是我遵循的教程:Use Multiple ng-view Single Page

有人可以帮忙指出我的错误或我应该怎么做才能使它们起作用吗?任何帮助将不胜感激,非常感谢。

【问题讨论】:

  • 或者我可以通过其他方式显示多个视图?谢谢!

标签: angularjs single-page-application angularjs-ng-include ng-view multiple-views


【解决方案1】:

您只需将/ 添加到href 中。

<a href="#/home">Home</a>

或者,如果您将 hashPrefix(使用 $locationProvider)设置为 ! 以进行 SEO,则为

<a href="#!/home">Home</a>

Angular 将$location 路径视为看起来像'/pathpart1/pathpart2'

【讨论】:

  • 谢谢,但将/! 添加到href 仍然不起作用。它不断重定向到相同的 url.. 所以由于显示的第一个路径是 hashPrefix,这是否意味着根是 /# 或如何?
  • 您必须在 $locationProvider 中声明 hashPrefix(请参阅文档),然后才能在 html 或 url 中使用它。这就是为什么我给你两个场景。对于 root 将使用 #/
  • 谢谢!最后通过添加 # 并在脚本中设置它来管理它!
【解决方案2】:

您尚未在配置中的路由提供程序中添加 /home 和 /features 等路由。 href 也应如@charlietfl 所示

【讨论】:

  • 感谢您的回答!它最终通过添加路由和 hashPrefix 来工作 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-24
  • 1970-01-01
  • 1970-01-01
  • 2013-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多