【问题标题】:Angular routing is not working properly?角度路由无法正常工作?
【发布时间】:2017-10-20 04:35:16
【问题描述】:

我正在尝试在 Angular js 中进行路由,并且服务器运行良好。但是角度路由无法正常工作,只有 main.html 页面进入 ng-view,second.html 没有出现。当点击 html 中的第一个和第二个时,相同的 mainController 不是 secondController。

HTML

<!Doctype html>

<html ng-app="myApp">
<meta charset=utf-8" />
 <head>


<script src="http://code.angularjs.org/snapshot/angular.min.js"></script>
<script src="http://code.angularjs.org/snapshot/angular-route.min.js">
</script>
<script type="text/javascript"src="app.js"></script>
<body>
<header>
    <li><a href="#/"><i></i>first</a></li>
    <li><a href="#/second"><i></i>Second</a></li>
</header>

    <div class = "container">



    <div ng-view> 

                </div>

        </body>     

main.html

<h1> this is main </h1>

second.html

 <h1> this is second </h1>

app.js

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

myApp.config(function ($routeProvider){

$routeProvider

.when('/',{
    templateUrl: 'pages/main.html',
    controller: 'mainController',
})

.when('/second',{
    templateUrl: 'pages/second.html',
    controller: 'secondController',
})

   });

     myApp.controller('mainController',
       ['$scope','$log','$location',function($scope,$log,$location){

        $log.info($location.path());
        console.log("first");

  }]);

   myApp.controller('secondController',
       ['$scope','$log','$location',function($scope,$log,$location){

        $log.info($location.path());
        console.log("second");

  }]);

【问题讨论】:

  • 你的控制台有错误吗?
  • “secondController”在哪里?

标签: javascript html angularjs


【解决方案1】:

问题是您的scripts,他们无法使用来自googleapis 的那个。

var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(function ($routeProvider) {
    $routeProvider
        .when('/', {
            template: '<h1>Main Page</h1>',
            controller: 'mainController',
        })
        .when('/second', {
            template: '<h1>{{ test }}</h1>',
            controller: 'secondController',
        })
});
myApp.controller('mainController',
    ['$scope', '$log', '$location', function ($scope, $log, $location) {
        $log.info($location.path());
        console.log("first");
    }])
    .controller('secondController', ['$scope', function ($scope) {
        $scope.test = 'Testing angular routes';
    }]);
<script src="https://code.angularjs.org/1.6.4/angular.js"></script>
<script src="https://code.angularjs.org/1.6.4/angular-route.min.js"></script>
<body ng-app="myApp">
<header>
    <li><a href="#!/"><i></i>first</a></li>
    <li><a href="#!/second"><i></i>Second</a></li>
</header>
<div class="container">
    <div ng-view>
    </div>
</div>
</body>

【讨论】:

  • 为什么不使用脚本运行
  • 不要将其更改为模板......不使用 templateUrl 运行(想要包含更大的 html 文件)
  • template 更改为templateUrl: 'pages/main.html'
猜你喜欢
  • 2016-10-24
  • 1970-01-01
  • 2019-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多