ngRoute不工作

时间:2015-03-22 09:13:57

标签: javascript html angularjs ngroute

我正在创建一个Angular App。文件结构如下:

index.html
login.html
js/index.js

index.html内容

<html>
    <head>
        <meta charset="utf-8" />
        <meta name="format-detection" content="telephone=no" />
        <meta name="msapplication-tap-highlight" content="no" />
        <!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />

        <link rel="stylesheet" type="text/css" href="css/index.css" />
        <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" />

        <title>Hello World</title>


        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
        <script href="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js" ></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular-route.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js" ></script>

    </head>
    <body ng-app="single-page-app">
    <div ng-view>   </div>
        <script type="text/javascript" src="cordova.js"></script>
        <script type="text/javascript" src="js/index.js"></script>
    </body>
</html>

js/index.js内容

var app1=angular.module('single-page-app',['ngRoute']);
app1.config(function($routeProvider){
      $routeProvider
          .when('/',{
                templateUrl: '../login.html'
          }).otherwise()
});

login.html内容

<form class="form-horizontal"  style="position:absolute;top:30%;left:20%">
  <div class="form-group col-xs-offset-2">
    <label for="userName" class="col-xs-3 control-label">UserName</label>
    <div class="col-xs-7">
      <input type="text" class="form-control col-xs-offset-1" id="userName" placeholder="UserName">
    </div>
  </div>
  <div class="form-group col-xs-offset-2">
    <label for="password" class="col-xs-3 control-label">Password</label>
    <div class="col-xs-7">
      <input type="password" class="form-control col-xs-offset-1" id="password" placeholder="Password">
    </div>
  </div>

  <div class="form-group">
    <div class=" col-xs-12">
      <button type="submit" class="btn btn-default col-xs-offset-4">Sign in</button>
    </div>
  </div>
</form>

当我使用index.html在服务器上打开python -m SimpleHTTPServer时,login.html中没有index.html个文件的内容。谁能告诉我为什么ng-route在上述情况下不起作用?

2 个答案:

答案 0 :(得分:2)

首先:templateUrl应该与应用根相对。我认为../login.html无效。

如果模板位于网站根目录中,请尝试使用

var app1=angular.module('single-page-app',['ngRoute']);
app1.config(function($routeProvider){
  $routeProvider
      .when('/',{
            templateUrl: '/login.html' // the edited line
      }).otherwise()
});

第二:从角度1.3开始,应将<base>标记添加到<head>部分。

<base href="/">

答案 1 :(得分:0)

首先,您必须在.otherwise()内部拥有某种价值,或者只是删除它。然后它会工作