how to redirect one html page to another using button click event in angularjs

74,783

Solution 1

In html,

<button ng-click="redirect()">Click</button>

In JS,

$scope.redirect = function(){
  window.location = "#/page.html";
}

Hope it helps.....

Solution 2

Would probably make a small modification.

inject $location and use:

$scope.redirect = function(){
  $location.url('/page.html');
}

The benefits of using $location over window.location can be found in the docs, but here's a summary as of (1.4.x)

https://docs.angularjs.org/guide/$location

enter image description here

If anyone knows how to make this redirect directly from the html in a cleaner way please let me know because I would prefer that sometimes over making a function in the controller...

Solution 3

In case you are using material design button 'md-button', you could do this.

I have tried giving attribute href, assigned with the link path. The redirection works well.

This could be tried if it is only redirection and there are no other tasks to be done before redirection.

<test1>
  <md-button href="/page.html">Click</md-button>
</test1>

Solution 4

I have succeeded navigation PAGE with below code in AngularJS.

$scope.click = function ()
{
    window.location = "/Home/Index/";
}
Share:
74,783
user3819122
Author by

user3819122

Updated on July 05, 2022

Comments

  • user3819122
    user3819122 about 2 years

    i am using angularjs directive to redirect another html page.i am writing click function inside directive but i am getting page name in alert box not redirect to another html page.

    sample.html:

    <test1>
    <button data-ng-click="click('/page.html')">Click</button>
    </test1>
    

    sample.js:

    app.directive('test1',['$location', function(location) {
        function compile(scope, element, attributes,$location) {
             return{
                 post:function(scope, element, iAttrs,$location) {
                     scope.click=function(path)
                     { 
                         alert("click"+path);
                         $location.path('/path');
                     };
                 }
             };
            }
    
            return({
                compile: compile,
                restrict: 'AE',
            });
    
        }]);
    

    i want to redirect page.html how to do this please suggest me. Thanks.