角度简单路由不起作用

时间:2015-12-19 11:56:37

标签: angularjs spring-boot thymeleaf

我正在构建单页应用,但我的角度路由有问题它不起作用。

我使用的是弹簧靴,百里香和角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>

一切都很好,但路由不在这里工作。

3 个答案:

答案 0 :(得分:3)

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

到目前为止我的回答

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

this spring blog所示,所有资源都放在目录

  • / META-INF /资源/
  • /资源/
  • /静态/
  • /公共/
你的类路径中的

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

现在到角度部分

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

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

如果您可以在Github上提供您的项目,我将会看一下。

答案 1 :(得分:1)

首先,请ng-app指令展示位置<body><html>代码

<body ng-app="ngViewExample">

模板网址

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);
 }
}

答案 2 :(得分:0)

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

public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/test").setViewName("test");
    }
}
相关问题