有没有办法使用按钮作为链接angularjs做导航页的简单方法 [英] Is there a simple way to use button to navigate page as a link does in angularjs
问题描述
在angularjs,我想用按钮
这样的,但我仍然需要按钮寻找。
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';
};
请注意:NOTE:事实上,当我用 location.href
导航,全被刷新,导航是不是angularjs的控制之下。如果我不使用环节,如何在JavaScript code导航页?
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?
我需要创建一个自定义指令IMPL呢?
Do I need to create a custom directive to impl it?
推荐答案
您 ngClick
是正确的;你只需要适当的服务。 $位置
是你在找什么。检查出文档的全部细节,但解决您的具体问题是这样的:
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' );
的 $位置
服务将根据您当前的设置中添加哈希(#),如果它是适当的,并确保没有页面重载发生。
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表明它在行动:<一href=\"http://plnkr.co/edit/870E3psx7NhsvJ4mNcd2?p=$p$pview\">http://plnkr.co/edit/870E3psx7NhsvJ4mNcd2?p=$p$pview.
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屋!