Is there a simple way to use button to navigate page as a link does in angularjs

后端 未结 7 1391
慢半拍i
慢半拍i 2020-12-23 21:31

In angularjs, I want to use button like this, but I still need the button looking.

相关标签:
7条回答
  • 2020-12-23 21:46

    For me, best solution is to use Angular router native directives with ui-sref like:

    <button ui-sref="state.name">Go!!</button>
    

    To understand that directive and get more options visit ui-router docs at:

    https://ui-router.github.io/docs/0.3.1/#/api/ui.router.state.directive:ui-sref

    : )

    0 讨论(0)
  • 2020-12-23 21:48
    <button type="button" href="location.href='#/nameOfState'">Title on button</button>
    

    Even more simple... (note the single quotes around the address)

    0 讨论(0)
  • 2020-12-23 21:54

    With bootstrap you can use

    <a href="#/new-page.html" class="btn btn-primary">
        Click
    </a>
    
    0 讨论(0)
  • 2020-12-23 21:54

    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

    0 讨论(0)
  • 2020-12-23 21:56

    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.

    0 讨论(0)
  • 2020-12-23 21:57

    You can also register $location on the scope in the controller (to make it accessible from html)

    angular.module(...).controller("...", function($location) {
      $scope.$location = $location;
      ...
    });
    

    and then go straight for the honey in your html:

    <button ng-click="$location.path('#/new-page.html')">New Page<button>
    
    0 讨论(0)
提交回复
热议问题