How to make a button with link in AngularJS

2

How to make a button with link / redirect in AngularJS?

html

<button class="btn btn-success" href="go('/cadastro.html')">Cadastra-se</button>

config

app.config(function($routeProvider, $locationProvider){

    .when('/', {
      templateUrl : 'views/login.html',
      controller     : 'LoginCtrl',
    })

    .when('/cadastro', {
      templateUrl : 'views/cadastro.html',
      controller     : 'CadastroCtrl',
    })

});
    
asked by anonymous 09.11.2016 / 21:23

4 answers

3

As far as I know, the button tag does not have the href attribute.

Another point, if you want to navigate to the route / registration , you need to change your location to '/ register' , removing the HTML way. Remember that you are accessing a route, not a physical path to your HTML.

If you use the code below, you should access the '/ register' route as configured in your module.

<a class="btn btn-success" href="#/cadastro')">Cadastra-se</a>

If you want to use a button accessing a method from your controller, it should look similar to the code below:

<button class="btn btn-success" ng-click="go(/cadastro)">Cadastra-se</button>

And in your controller:

$scope.go = function(path){
     $location.path(path);
}

The object $ location should be included as a code dependency above. It aims to give you an interface to access the URL of the browser. Any modification made to the URL will reflect on the $location object, and vice versa.

    
09.11.2016 / 21:40
0

would look like this:

<button class="btn btn-primary" ui-sref="cadastro" >
  <span class="glyphicon glyphicon-plus"></span>
  <span >
    Cadastrar
  </span>
</button>

It will use your specified path in your config to redirect.

    
09.11.2016 / 21:44
0

This code is almost ready. Just need to add the function in the controller to change the route:

$scope.go = function ( path ) {
    $location.path( path ); 
 };

But, as you are apparently using the bootstrap, I believe you can use the tag instead of the button, like this:

<a class="btn btn-success" href="cadastro.html'">Cadastra-se</a>

So you do not need the function in the controller.

    
09.11.2016 / 21:45
0

Vanilla

Via Javascript

<input type="button" 
    onclick="location.href='http://servidor.com.br';" 
    value="Visitar servidor.com.br" 
/>

Via form action

<form action="http://servidor.com.br">
    <input type="submit" value="Visitar servidor.com.br" />
</form>

Angular

Via directive:

.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 );
      });
    });
  };
});

Usage:

<button go-click="http://servidor.com.br">Visitar servidor.com.br</button>

( Font )

    
09.11.2016 / 21:57