gpt4 book ai didi

javascript - AngularJs 路由没有错误但不工作

转载 作者:行者123 更新时间:2023-11-30 15:20:38 24 4
gpt4 key购买 nike

我正在创建一个使用路由的演示应用程序。即使控制台没有错误,我也看不到我的内容。这里可能有什么问题。我创建了两个不同内容的单独 html 文件

<html>

<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.js"></script>
<script src = "js/junk.js"></script>
</head>

<body ng-app="junkapp">
<div ng-controller = "junkController">
<ul>
<li><a href="#/">Home</a></li>
<li><a href="#/first">First</a></li>
<li><a href="#/second">Second</a></li>
</ul>
<div ng-view>
</div>
</div>
</body>
</html>

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

app.controller("junkController", function($scope){

app.config(function($routeProvider) {
$routeProvider

// route for the home page
.when('/', {
templateUrl : 'junk.html',
})

// route for the about page
.when('/first', {
templateUrl : 'first.html',
})

// route for the contact page
.when('/second', {
templateUrl : 'second.html',
});
});
});

最佳答案

配置不应该在 Controller 之下。

We can’t define routes in a controller or in a service since the configuration needs to happen before it gets injected into anything we want to use it in. Any configuration we do to providers in the config function will allow us to access pre-configured instances of these providers when they are injected.

var app = angular.module('junkapp',['ngRoute']);
app.config(function($routeProvider) {
$routeProvider.
when('/', {
templateUrl : "home.html"
}).

when('/first', {
template : "<p>Hi First</p>"
}).

when('/second', {
template : "<p>Hi second</p>"
});
});

app.controller("junkController", function($scope){
$scope.text = "Welcome";
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.js"></script>
<script type="text/ng-template" id="home.html">
<p>Hi Home</p>
</script>
<body ng-app="junkapp">
<div ng-controller = "junkController">
<ul>
<li><a href="#/">Home</a></li>
<li><a href="#/first">First</a></li>
<li><a href="#/second">Second</a></li>
</ul>
<div ng-view>
</div>
</div>
</body>

关于javascript - AngularJs 路由没有错误但不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43782995/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com