In angularjs, I want to use button
like this, but I still need the button looking.
<button href="#/new-page.html">New Page<button>
As a
(link) does
<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: 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?
Best Answer
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: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:
And then you could use it on anything:
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.