是否有一种简单的方法可以像 angularjs 中的链接一样使用按钮导航页面 [英] Is there a simple way to use button to navigate page as a link does in angularjs
问题描述
在 angularjs 中,我想像这样使用 button
,但我仍然需要寻找按钮.
In angularjs, I want to use button
like this, but I still need the button looking.
<button href="#/new-page.html">New Page<button>
正如a
(链接)所做的
<a href="#/new-page.html">New Page</a>
还有比这更简单的方法吗?
Is there a simpler way than this?
<button ng-click="newPage()">New Page<button>
$scope.newPage = function (){
location.href = '#/new-page.html';
};
注意:其实我以前用location.href
导航的时候,整体刷新,导航不在angularjs的控制下.如果我不使用链接,如何在 javascript 代码中导航页面?
Note: Acutally, when I used to location.href
for navigation, the whole is refreshed and the navigation is not under the control of angularjs. If I don't use link, how to navigate page in javascript code?
我是否需要创建自定义指令来实现它?
Do I need to create a custom directive to impl it?
推荐答案
您的 ngClick
是正确的;您只需要正确的服务.$location
正是您要找的.查看文档以获取完整详细信息,但您的具体问题的解决方案是:
Your ngClick
is correct; you just need the right service. $location
is what you're looking for. Check out the docs for the full details, but the solution to your specific question is this:
$location.path( '/new-page.html' );
$location
服务将根据您当前的设置添加适当的哈希 (#),并确保不会发生页面重新加载.
The $location
service will add the hash (#) if it's appropriate based on your current settings and ensure no page reload occurs.
如果您愿意,您还可以使用指令做一些更灵活的事情:
You could also do something more flexible with a directive if you so chose:
.directive( 'goClick', function ( $location ) {
return function ( scope, element, attrs ) {
var path;
attrs.$observe( 'goClick', function (val) {
path = val;
});
element.bind( 'click', function () {
scope.$apply( function () {
$location.path( path );
});
});
};
});
然后你可以在任何事情上使用它:
And then you could use it on anything:
<button go-click="/go/to/this">Click!</button>
有很多方法可以改进这个指令;这只是为了展示可以做些什么.这是一个 Plunker 演示它的操作:http://plnkr.co/edit/870E3psx7NhsvJ4mNcd2?p=preview.
There are many ways to improve this directive; it's merely to show what could be done. Here's a Plunker demonstrating it in action: http://plnkr.co/edit/870E3psx7NhsvJ4mNcd2?p=preview.
这篇关于是否有一种简单的方法可以像 angularjs 中的链接一样使用按钮导航页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!