Mel*_*Mel 3 javascript browser-history angularjs
我想$locationProvider在AngularJS中使用该服务而不在我的网站中呈现新的HTML模板ng-view.
我有一个div元素,通过ng-show绑定到数据元素的存在按需显示.我想通过它将其连接到浏览器位置,$locationProvider但保持在同一模板中.
模板:
<div> other stuff ... </div>
<div ng-show="model">{{ model.element }}</div>
Run Code Online (Sandbox Code Playgroud)
控制器:
Controller = function($scope, $location) {
$scope.show = function() {
$scope.model = model; // show div
}
$scope.hide = function() {
$scope.model = null; // hide div
}
}
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚如何$location在这个中集成服务.如果history.pushState直接设置,AngularJS也会覆盖该位置.
使用源码,Luke :-) http://code.angularjs.org/1.0.0/angular-1.0.0.js
如果你看一下ngViewDirective(它实际上非常简单),它只会捕获'$ routeChangeSuccess'事件并相应地更改视图.
因此,您可以捕获$ routeChangeSuccess,然后将$ route注入您的控制器,检查新路由是否是您想要的路径,并相应地显示.(我想:D)
这可能有效(未经测试):
//declare a route so angular knows to broadcast about it when it's hit
//We aren't declaring any actions for the route though,
//since below we define custom actions
myApp.config(function($routeProvider) {
$routeProvider.when('/superman', {});
});
function SupermanCtrl($scope, $route) {
$scope.$on('$routeChangeSuccess', function() {
//If this doesn't work, console.log $route.current to see how it's formatted
if ($route.current == '/superman')
$scope.show = true;
else
$scope.show = false;
});
}
Run Code Online (Sandbox Code Playgroud)
我希望它有效,如果没有,它应该足够开始.我鼓励你阅读ngViewDirective,如果这不起作用,搜索'$ routeChangeSuccess'并弄清楚如何/为什么它被广播.