Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a simple way to use button to navigate page as a link does in 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>

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?

like image 430
Henry Leu Avatar asked Apr 06 '13 06:04

Henry Leu


People also ask

How do I turn a button into a link?

Adding styles as button to a link: This method create a simple anchor tag link and then apply some CSS property to makes it like a button. Using form tags: This method uses form tag and button tag. When button is clicked then the form action attribute is called and web page redirect into the given location.


3 Answers

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>

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.

like image 188
Josh David Miller Avatar answered Oct 16 '22 14:10

Josh David Miller


With bootstrap you can use

<a href="#/new-page.html" class="btn btn-primary">
    Click
</a>
like image 24
rtp Avatar answered Oct 16 '22 12:10

rtp


If you're OK with littering your markup a bit, you could do it the easy way and just wrap your <button> with an anchor (<a>) link.

<a href="#/new-page.html"><button>New Page<button></a>

Also, there is nothing stopping you from styling an anchor link to look like a <button>


as pointed out in the comments by @tronman, this is not technically valid html5, but it should not cause any problems in practice

like image 21
Zach Lysobey Avatar answered Oct 16 '22 13:10

Zach Lysobey