理解angularjs中的路由和模板html,简单的例子是可能的

understanding routes and templates html in angularjs, simples example possible

本文关键字:简单 angularjs 路由 理解 html      更新时间:2023-09-26

我正在尝试将angularjs嵌入到我现有的asp.net mvc4应用程序中。

(视图/共享/)_Layout.cshtml

<html data-ng-app="myApp">
     <head>
       <script src="~/Scripts/angular.min.js"></script>
       <script src="/js/main.js"></script>     
     </head>
   <body>
        @RenderBody()
   </body>
</html>

/js/main.js

var app = angular.module("myApp", []);
module.config(function ($routeProvider) {
    $routeProvider.when("/topics", {
        controller: "topicsController",
        templateUrl: "/js/templates/topicsView.html"
    });
    $routeProvider.otherwise({ redirectTo: "/" });
});
app.controller("topicsController", function ($scope) {
    $scope.testData = "some dummy data";
});

/js/templates/topicsView.html

<h1>topics template view, dummy object </h1>
{{ testData }}

以及/Views/Home/Index.cshtml内部

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

我试图使用#/topicsurl导航到/topics,但没有任何内容(空白页,而不是404),甚至templates/topicsView.html 中的h1标题也没有

我做错了什么?

您忘记包含ngRoute模块。试试这个:

var app = angular.module("myApp", ['ngRoute']);

创建angular主应用程序模块时,需要将angular-routes.js和angular.js一起包含,然后将ngRoutes模块作为依赖项包含在内。