Angular ui-sref和ui-view不能一起工作

时间:2017-04-28 13:16:42

标签: javascript angularjs html5 routing

我有一个简单的html文件:

<div class="header">
  <div class="navbar navbar-inverse">
    <div class="container">
      <div class="navbar-header">

        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#js-navbar-collapse">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>

        <a class="navbar-brand" ui-sref="main">Show view</a>
      </div>
    </div>
  </div>
</div>

<div class="container">
  <div ui-view=""></div>
</div>

container div我想设置正确的视图模板。

这是我的路线:

app.controller('DefaultCtrl', function ($route) {
  $route.reload();
});

app.config(function ($stateProvider, $httpProvider) {
  $httpProvider.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';

  $stateProvider
    .state('main', {
      url: '/',
      templateUrl: '../views/main.html',
      controller: 'DefaultCtrl'
    });
})

和main.html文件:

<div class="container">
 <p><h3>Other view for container</h3></p>
</div>

问题是,当我点击Show view处的链接时,没有任何反应。文字Other view for container未显示。 怎么解决这个?

1 个答案:

答案 0 :(得分:0)

检查下面的代码,我已经添加了所有必需的注入器,如果你使用templateURL,请使用app目录中的路径,不要使用相对路径。

var app = angular.module('mainapp',['ngRoute','ui.router']);

app.controller('DefaultCtrl', function ($route) {
  $route.reload();
});

app.config(function ($routeProvider,$stateProvider) { 
 $stateProvider
    .state('main', {
      url: '/',
      template: '<h1> Main View </h1>',
      controller: 'DefaultCtrl'
    });
 
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<script src="https://unpkg.com/angular-ui-router/release/angular-ui-router.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>

<div ng-app ='mainapp'>
<div class="header">
  <div class="navbar navbar-inverse">
    <div class="container">
      <div class="navbar-header">

        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#js-navbar-collapse">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>

        <a class="navbar-brand" ui-sref="main">Show view</a>
      </div>
    </div>
  </div>
</div>

<div class="container">
  <div ui-view=""></div>
</div>
</div>