简体   繁体   中英

switch views from one page to another when the button is clicked in angular JS

I am new to angular JS.How can I redirect to another page when the button is clicked. My code here

var app = angular.module("plunker", [])
.config(function ($routeProvider, $locationProvider, $httpProvider) {

$routeProvider.when('/home',
{
  templateUrl:    'home.html',
  controller:     'HomeCtrl'
});
$routeProvider.when('/about',
{
  templateUrl:    'about.html',
  controller:     'AboutCtrl'
});
$routeProvider.when('/contact',
{
  templateUrl:    'contact.html',
  controller:     'ContactCtrl'
});
$routeProvider.otherwise(
{
  redirectTo:     '/home',
  controller:     'HomeCtrl', 
}

); });

app.controller('NavCtrl', 
['$scope', '$location', function ($scope, $location) {  
$scope.navClass = function (page) {
var currentRoute = $location.path().substring(1) || 'home';
return page === currentRoute ? 'active' : '';
};
   }]);

app.controller('AboutCtrl', function($scope, $compile) {
console.log('inside about controller');


});

app.controller('HomeCtrl', function($scope, $compile) {
console.log('inside home controller');

//redirect when button click function Cntrl ($scope,$location) { $scope.redirect = function(){ window.location.href = '/about'; } }

});

app.controller('ContactCtrl', function($scope, $compile) { console.log('inside contact controller');

});

my html markup is

<div ng-controller="Cntrl">
    <button class="btn btn-success" ng-click="changeView('about')">Click Me</button>
</div>

You entered :

How to get this.help me to solve this .

Just use a standard HTML link :

<div ng-controller="Cntrl">
    <a class="btn btn-success" ng-href="#/about">Click Me</a>        
</div>

No need to create a scope function for that. You can also handle that dynamically thanks to ng-href :

<div ng-controller="Cntrl">
    <a class="btn btn-success" ng-href="#/{{view}}">Click Me</a>        
</div>

Last thing, you should consider using ui-router which handle even better this cases

Why do you need to send the view as a param:

Try this:

$scope.changeView = function() {
            $location.path(#/about); 
        }

If solution that Cétia presented does not work, then it is possible that you do not have your routes defined. Make sure that you have your route defined withing app.js like this :

  app.config(['$routeProvider', function ($routeProvider) {
        $routeProvider
            .when('/Login', {
                templateUrl: 'Navigate/LoginView',
                controller: 'someLoginController'
            })

]);

You can as well use angulars state provider (do some research) and from state provider you can access your routes within html as :

<a href="state.routName" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM