【发布时间】:2013-11-12 07:46:07
【问题描述】:
我是 AngularJs 的新手。 我想要做的是更新 hashchange 事件的页面。
我目前所做的(并且知道这不是“正确”的方式)是:
<!DOCTYPE html>
<html>
<head>
<style>
#hashdrop {
display:block;
border: 1px solid gray;
width: 500px;
overflow: auto;
background-color: rgb(241,241,241);
border-radius: 4px;
text-align: center;
vertical-align: middle;
line-height: 100px;
font-size: large;
height: 100px;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script>
var example = function($scope) {
$scope.lastHash = location.hash.slice(1);
$(window).on('hashchange', function (event) {
$scope.lashHash = location.hash.slice(1);
$scope.$apply();
});
};
</script>
<meta charset=utf-8 />
</head>
<body ng-app ng-controller="example">
<div id="hashdrop" >
{{lastHash}}
</div>
</body>
</html>
(这可以复制粘贴到一个空白的 html 文件中并运行。jsbin 没有正确检测到 haschange,对我来说。)
这真的行不通。由于某种原因,该值未更新,我认为 angularjs 中有一个“正确”的方法。
我想了解如何正确执行此操作,更具体地说,如何更正此示例中的代码以“角度方式”工作。
谢谢!
更新 1 好的,看了关于$location的评论后,我找到了一些信息并将我的应用程序更改为:
<!DOCTYPE html>
<html>
<head>
<style>
#hashdrop {
display:block;
border: 1px solid gray;
width: 500px;
overflow: auto;
background-color: rgb(241,241,241);
border-radius: 4px;
text-align: center;
vertical-align: middle;
line-height: 100px;
font-size: large;
height: 100px;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script>
angular.module('example',[]).config(function($locationProvider, $routeProvider) {
$locationProvider.html5Mode(true);
});
var example = function($scope, $location) {
};
</script>
<meta charset=utf-8 />
</head>
<body ng-app="example" ng-controller="example">
<div id="hashdrop" >
Hash = {{$location.hash()}}
</div>
</body>
</html>
还是不行。输出中没有显示任何内容..
【问题讨论】:
-
你为什么不使用 routeChange 事件来获取路线变更通知更多信息在这里docs.angularjs.org/api/ngRoute.$route
-
您没有在范围内公开
$location。没有名称为$location的$scope模型。
标签: javascript angularjs hashchange