238

I am trying to use the ng-click feature of AngularJS to switch views. How would I go about doing this with the code below?

index.html

 <div ng-controller="Cntrl">
        <div ng-click="someFunction()">
            click me
        <div>
    <div>

controller.js

  function Cntrl ($scope) {
        $scope.someFunction = function(){
            //code to change view?
        }
    }
Damjan Pavlica
  • 31,277
  • 10
  • 71
  • 76
The_Brink
  • 2,649
  • 2
  • 16
  • 18

8 Answers8

315

In order to switch between different views, you could directly change the window.location (using the $location service!) in index.html file

<div ng-controller="Cntrl">
        <div ng-click="changeView('edit')">
            edit
        </div>
        <div ng-click="changeView('preview')">
            preview
        </div>
</div>

Controller.js

function Cntrl ($scope,$location) {
        $scope.changeView = function(view){
            $location.path(view); // path not hash
        }
    }

and configure the router to switch to different partials based on the location ( as shown here https://github.com/angular/angular-seed/blob/master/app/app.js ). This would have the benefit of history as well as using ng-view.

Alternatively, you use ng-include with different partials and then use a ng-switch as shown in here ( https://github.com/ganarajpr/Angular-UI-Components/blob/master/index.html )

Ferruccio
  • 98,941
  • 38
  • 226
  • 299
ganaraj
  • 26,841
  • 6
  • 63
  • 59
  • I'm getting an error that says hash is not function of $location. – The_Brink Jun 12 '12 at 23:44
  • I don't see hash as being part of the $location object, but there is a $$hash variable so is that it and if so it doesn't work. – The_Brink Jun 12 '12 at 23:59
  • OK, I found out how to do it. $location.path(view); (http://docs.angularjs.org/guide/dev_guide.services.$location) – The_Brink Jun 13 '12 at 00:07
  • @The_Brink Thank you for the edit. I dont know why it was rejected. I made changes to reflect what I was attempting to say. – ganaraj Jun 13 '12 at 11:23
  • Edited the response. It should be .path not .hash see http://docs.angularjs.org/api/ng.$location and http://docs.angularjs.org/guide/dev_guide.services.$location – Misko Hevery Jun 13 '12 at 17:49
  • 2
    The best thing to do actually is just make a normal link. `Edit` Angular will take make sure that the click does not create a page reload. This behavior can be modified so that it triggers a reload if that is desired. – Anthony Martin Oct 16 '13 at 04:43
  • There's also `$location.url('/path?query')`, which you can use if you need to include a query string. `$location.path()` seems to strip query strings. – z0r Nov 01 '13 at 00:27
38

The provided answer is absolutely correct, but I wanted to expand for any future visitors who may want to do it a bit more dynamically -

In the view -

<div ng-repeat="person in persons">
    <div ng-click="changeView(person)">
        Go to edit
    <div>
<div>

In the controller -

$scope.changeView = function(person){
    var earl = '/editperson/' + person.id;
    $location.path(earl);
}

Same basic concept as the accepted answer, just adding some dynamic content to it to improve a bit. If the accepted answer wants to add this I will delete my answer.

PW Kad
  • 14,953
  • 7
  • 49
  • 82
  • 8
    a total nitpick, but FYI, a `url` is actually the __full__ web address, including the protocol (http://) and everything. As implied by `$location.path()` your variable is better described as a `path`. – Zach Lysobey Dec 17 '13 at 21:41
  • But it requires a $rootScope.$digest(); or $scope.$apply(); in order to make it move without a delay. – Raz Jan 16 '18 at 07:24
23

I've got an example working.

Here's how my doc looks:

<html>
<head>
    <link rel="stylesheet" href="css/main.css">
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular-resource.min.js"></script>
    <script src="js/app.js"></script>
    <script src="controllers/ctrls.js"></script>
</head>
<body ng-app="app">
    <div id="contnr">
        <ng-view></ng-view>
    </div>
</body>
</html>

Here's what my partial looks like:

<div id="welcome" ng-controller="Index">
    <b>Welcome! Please Login!</b>
    <form ng-submit="auth()">
        <input class="input login username" type="text" placeholder="username" /><br>
        <input class="input login password" type="password" placeholder="password" /><br>
        <input class="input login submit" type="submit" placeholder="login!" />
    </form>
</div>

Here's what my Ctrl looks like:

app.controller('Index', function($scope, $routeParams, $location){
    $scope.auth = function(){
        $location.url('/map');
    };
});

app is my module:

var app = angular.module('app', ['ngResource']).config(function($routeProvider)...

Hope this is helpful!

Richard
  • 138
  • 1
  • 1
  • 9
Cody
  • 9,785
  • 4
  • 61
  • 46
12

The method used for all previous answers to this question suggest changing the url which is not necessary, and I think readers should be aware of an alternative solution. I use ui-router and $stateProvider to associate a state value with a templateUrl which points to the html file for your view. Then it is just a matter of injecting the $state into your controller and calling $state.go('state-value') to update your view.

What is the difference between angular-route and angular-ui-router?

Community
  • 1
  • 1
Gavin Palmer
  • 1,220
  • 15
  • 25
5

There are two ways for this:

If you are using ui-router or $stateProvider, do it as:

$state.go('stateName'); //remember to add $state service in the controller

if you are using angular-router or $routeProvider, do it as:

$location.path('routeName'); //similarily include $location service in your controller
Mostafiz
  • 7,243
  • 3
  • 28
  • 42
  • On thing that tripped me up was using the route name instead of the state name... i.e. it should be "main" instead of "/main" – Ben Schmidt Feb 01 '17 at 22:22
3

Without doing a full revamp of the default routing (#/ViewName) environment, I was able to do a slight modification of Cody's tip and got it working great.

the controller

.controller('GeneralCtrl', ['$route', '$routeParams', '$location',
        function($route, $routeParams, $location) {
            ...
            this.goToView = function(viewName){
                $location.url('/' + viewName);
            }
        }]
    );

the view

...
<li ng-click="general.goToView('Home')">HOME</li>
...

What brought me to this solution was when I was attempting to integrate a Kendo Mobile UI widget into an angular environment I was losing the context of my controller and the behavior of the regular anchor tag was also being hijacked. I re-established my context from within the Kendo widget and needed to use a method to navigate...this worked.

Thanks for the previous posts!

beauXjames
  • 8,222
  • 3
  • 49
  • 66
2
Firstly you have to create state in app.js as below

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

and use below code in controller

 $location.path('login'); 

Hope this will help you

Vaishali Tekale
  • 101
  • 2
  • 2
2

This little function has served me well:

    //goto view:
    //useage -  $scope.gotoView("your/path/here", boolean_open_in_new_window)
    $scope.gotoView = function (st_view, is_newWindow)
    {

        console.log('going to view: ' + '#/' + st_view, $window.location);
        if (is_newWindow)
        {
            $window.open($window.location.origin + $window.location.pathname + '' + '#/' + st_view, '_blank');
        }
        else
        {
            $window.location.hash = '#/' + st_view;
        }


    };

You dont need the full path, just the view you are switching to

Shawn Dotey
  • 616
  • 8
  • 11