Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

AngularJS : How do I switch views from a controller function?

am attempting to utilize the ng-click feature of AngularJS to switch views. How might I approach doing this with the code underneath?

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?
}
}
by

3 Answers

akshay1995
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.
sandhya6gczb
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
}
}
pankajshivnani123
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

Login / Signup to Answer the Question.