Angularjs Route似乎不起作用

时间:2014-07-27 20:33:39

标签: angularjs

我有4个文件index.html,test.html,module.js和name.json

出于某种原因,它似乎不适用于我的本地主机。我的代码错误或我的路线错误我只想显示我的test.html页面。

的index.html

<!DOCTYPE html>

<html data-ng-app = "mysite">

<head>

    <title>Practice with Angular</title>

</head>

<body>

    <div>

        <div data-ng-view = ""></div>

    </div>

    <script type="text/javascript" src = "http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js"></script>
    <script type="text/javascript" src = "module.js"></script>

</body>

</html>

的test.html

<div>

    <input data-ng-model = "search" type = "text">

    <table>

        <tr>

            <th><a href="" data-ng-click = "sortfield = 'name'">Names</a></th>

        </tr>

        <tr data-ng-repeat = "x in names | filter : search | orderBy : sortfield">

            <td>

                {{x.name}}

            </td>

        </tr>

    </table>

    <p>Welcome {{search}}</p>

</div>

module.js

var app = angular.module("mysite", []);

app.config(function($routeProvider){

    $routeProvider
        .when("/", {

            controller : "name-controller",
            templateUrl : "test.html"


        })
        .otherwise({ redirectTo : "/"});

});

app.controller("name-controller", function($scope, $http){

    $http.get("name.json").success(function(data){

        $scope.names = data;

    });

});

name.json

[
{"name" : "nelson"},
{"name" : "shirley"},
{"name" : "jenny"},
{"name" : "darrick"},
{"name" : "yen"},
{"name" : "mom"},
{"name" : "dad"},
{"name" : "coreen"}
]

2 个答案:

答案 0 :(得分:0)

我认为ng-view指令应该写成:<div data-ng-view></div>。您还需要在test.html中命名控制器。

答案 1 :(得分:0)

请见http://plnkr.co/edit/t6qgL9P7zDBfEUp6385N?p=preview

a)请添加对angular-route.js的引用 b)将ngRoute注入角度模块var app = angular.module('mysite', ['ngRoute']);

<!DOCTYPE html>
<html data-ng-app = "mysite">

  <head>
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular-route.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>


<body >

  <div ng-view="">

  </div>
  </body>

</html>

JS:

var app = angular.module('mysite', ['ngRoute']);
app.config(function($routeProvider){

    $routeProvider
        .when("/", {

            controller : "name-controller",
            templateUrl : "test.html"


        })
        .otherwise({ redirectTo : "/"});

});
app.controller("name-controller", function($scope, $http){

    $http.get("name.json").success(function(data){

        $scope.names = data;

    });

});