【问题标题】:ngRoute is not changing view when click of <a> tag单击 <a> 标签时,ngRoute 不会更改视图
【发布时间】:2017-07-20 00:07:38
【问题描述】:

我是 Angular JS 的新手,遇到了一个问题……我不知道发生了什么。请帮助解决它。

我有索引文件并且 app.js 已连接,app 正在使用 ngRoute...见下面的代码。

var app = angular.module('routedapp',['ngRoute']);
//app.config("$routeProvider",function($routeProvider)) also tried this

app.config(function($routeProvider) {
$routeProvider.when("/",{
    templateUrl: "views/home.html"
})
.when("/post",{
    templateUrl: "views/post.html"
})
.when("/contact",{
    templateUrl: "views/contact.html",
    controller: "contactCtrl"
})

})
app.controller('contactCtrl', function($scope){
$scope.lalteen = function(){
    console.log("clicked");
}

})

并且有 4 页... index.html 、 home.html 、 post.html 和 contact.html。

//index.html代码

<html>
<head>
<title>Routed</title>

</head>
<body ng-app="routedapp" >
<div>welcome</div>
<div>
    <p ng-click="lalteen()">click me</p>
</div>

<!-- views here-->
<div ng-view >
</div>
    <script src="vendor/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-route.js"></script>
<script src="app.js"></script>
</body>
</html>

最初,当 index.html 页面加载时,它会在视图中显示 home.html 内容,home.html 有 3 个指向主页、帖子和联系页面的链接......当我点击任何一个时......它不会改变查看但不断更改网址,例如:

http://localhost/route/#!/#%2F  //for home <a> tag
http://localhost/route/#!/#contact //for contact <a> tag and other like that.

PS:以下是我在 post.html、home.html 和 contact.html 中的内容结构,看起来像......

<div>This is post page</div>
<p><a href="#/">Home<a/></p><br>
<p><a href="#/post" ng-click="lalteen()">post</a></p><br>
<p><a href="#/contact">contact</a></p><br>

我是新人...请不要介意我的冗长解释...谢谢

【问题讨论】:

    标签: angularjs angular-ui-router ngroute route-provider angularjs-ng-route


    【解决方案1】:

    更新

    好的,所以我可以弄清楚您要做什么以及为什么您的路由不起作用。

    首先还原更改,以便您拥有原始格式的链接部分:

    <div>This is post page</div>
    <p><a href="#">Home<a/></p><br>
    <p><a href="#post" ng-click="lalteen()">post</a></p><br>
    <p><a href="#contact">contact</a></p><br>
    

    然后在您的脚本中注入$locationProvider 服务并将默认路由前缀设置为空字符串。

     app.config(function($routeProvider, $locationProvider) {
       //note that this line does the magic ;)
       $locationProvider.hashPrefix('');
       //normal routing here
       $routeProvider.when("/",{
         templateUrl: "views/home.html"
       })
       .when("/post",{
         templateUrl: "views/post.html"
       })
       .when("/contact",{
         templateUrl: "views/contact.html",
         controller: "contactCtrl"
       })
     })
    

    为您创建了一个工作 plunker here

    【讨论】:

    • 我从链接中删除了 ng-click 和 #...但是链接仍然没有导航到所需的模板...
    • 你能创建一个 plunker 什么的吗?
    • 兄弟,请查看链接test.kashifdesigns.com/route ...您可以在检查元素的网络中文件...对不起,我不知道如何在 plunker 中添加我的代码...
    • 你做得很好...希望你的生活也能成功...结束)...你能帮我选择正确的语言/领域吗?它有很好的范围和收入...
    猜你喜欢
    • 1970-01-01
    • 2020-08-17
    • 1970-01-01
    • 2014-11-16
    • 1970-01-01
    • 2018-11-17
    • 2011-08-24
    • 1970-01-01
    • 2011-05-20
    相关资源
    最近更新 更多