Angular 简单路由不起作用

Angular simple routing is not working

我正在尝试构建单页应用程序,但我遇到了问题 angular 路由不起作用。

我正在使用 spring boot、thymeleaf 和 angular 1.4.8.

我基于这个例子https://code.angularjs.org/1.4.8/docs/api/ngRoute/directive/ngView

这是我的主控制器:

@Controller
public class HomeController {
    @RequestMapping(value = "/")
    public String index(){
        return "index";
    }
}

这是我的 index.html

<!DOCTYPE html>
<html>
<head ng-app="ngViewExample">
    <title></title>
</head>
<body>
<div ng-controller="MainCtrl as main">
        <a href="#/test">test</a>

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

<script type="text/javascript" th:src="@{/js/lib/angular.js}" />
<script type="text/javascript" th:src="@{/js/lib/angular-route.js}" />
<script type="text/javascript" th:src="@{/js/lib/angular-resource.js}" />
<script type="text/javascript" th:src="@{/js/lib/underscore.js}" />
<script type="text/javascript" th:src="@{/js/lib/restangular.js}" />
<script type="text/javascript" th:src="@{/js/src/index.js}" />
</body>
</html>

index.js

 var home = angular.module('ngViewExample', ['ngRoute']);

home.config(['$routeProvider',
    function ($routeProvider) {
        $routeProvider
            .when('/test', {
                templateUrl: 'test.html',
                controller: 'TestCtrl',
                controllerAs: 'test'
            })
    }])

    .controller('MainCtrl',
        function() {

        })
    .controller('TestCtrl', 
        function() {

    });

以及我希望传递给 ng-view 的内容

test.html

<div>
    Hello
</div>

一切都加载正常,但路由在这里不起作用。

你把test.html放在哪里了。它应该在 /resources/static 文件夹中。如果在 /resources/templates 中,它将由 thymeleaf 处理,需要在 ViewControllerRegistry

中添加
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/test").setViewName("test");
    }
}

首先,请ng-app指令放置<body><html>标签

<body ng-app="ngViewExample">

模板url

templateUrl: 'test'

MvcConfig.java

@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
  @Override
  public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/test").setViewName("test");  
  }
}

SpringBootApp

@SpringBootApplication
@ComponentScan(basePackages = {"com.example.spring"})
public class SpringAngularApplication {

   public static void main(String[] args) {
     SpringApplication.run(SpringAngularApplication.class, args);
 }
}

你昨天把这个问题联系到了我:

这是我目前的答案

让我们从如何通过Spring引导提供静态内容开始

如图this spring blog所有资源放在目录

  • /META-INF/resources/
  • /资源/
  • /静态/
  • /public/

在您的类路径中添加为静态资源。因此,例如,只需将 index.html 放入类路径中的 /public/ 目录中,就不再需要 HomeController

现在进入angular部分

首先将 ng-app 指令放在 <html><body> 标签中。 到目前为止,我看不出您的 angular 代码有任何问题。您能否验证部分 HTML 在 /test 端点可用?如果没有,请按照我上面告诉你的步骤操作。只需将 test.html 放入类路径中的 /public/ 目录即可。

如果您打开浏览器开发工具并重新加载页面,控制台是否有任何错误?

如果你能在 Github 上提供你的项目,我会看一看。