2

AngularJs code to navigate to another page on a button click event. I have catch the button click event but cannot navigate to another page. The following is my code: HTML file:

<!DOCTYPE html>

<html>

<head>

<script src="js/angular.min.js"></script>

<script src="js/app/home.js"></script>

</head>

<body ng-app="myapp">

    <div ng-controller="TestCtrl">

      <button ng-click="clicked()">Click me!</button>

</body>

</html>

And the javascript file is:

var VLogin = angular.module('myapp',[]);

VLogin.controller('TestCtrl', ['$scope',function($scope) {

    $scope.clicked = function(){   

        $location.path('/test.html');
    }

}]);
1

3 Answers 3

12

Try like as shown below...

In html,

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

In JS,

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

I hope it helps you...

Sign up to request clarification or add additional context in comments.

3 Comments

SDK: Yes its work for me.. But in the path i have to change like this : window.location = "../www/index.html";
dont forget to accept this answer if you find it useful:-)
hi, I want the button to redirect to another component's html page. how can that be done?
4

You can use $location.path('/newPageUrl') to navigate to new page.

Read here for more information on $location.

Edit: The correct controller code would be (after adding $location as a dependency):-

VLogin.controller('TestCtrl', ['$scope', '$location',function($scope, $location) {

$scope.clicked = function(){   

    $location.path('/test.html');
}

}]);

3 Comments

Abhishek Jain: I have used the $location.path('/newPageUrl') code but it's not working for me.
You have to pass $location service to controller
But use absolute path redirection with $window Here you have it: plnkr.co/edit/nClPD7mFdF4Rz2VmhZSJ?p=preview
1

If you want to navigate to another page onclick I suggest using good old 'link'

<a href="/another-page">Go to another page</a>

Unless you have to do something before redirection than use $location service proposed by Abhishek Jain

3 Comments

Teq1:I want to navigate inside button click event function.
@BibinJose using my solution you do :) But as I mentioned use good old href unless you have to do something before redirection than use $location service which is better to test.
@Teq1 can't put a inside or outside of button - htmlangular validation fails

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.