rex
rex

Reputation: 339

change ngview from within function

I am using templates to build my app. Basically have one main page, and then I am loading others pages thru it using ng-view. The href links in the index.html work fine. But I also want to be able to change ng-view within js functions as well. How is this done?

I tried to go to the red page using $location.path, but nothing seems to happen besides printing to the console. Before that i tried using $window.location.href(), which did go to the page, but dropped the index.html container, breaking the app.

edit: As pointed out in Siddhesh's answer comments, it works if not used with $locationProvider.html5Mode(true);. But I would like to keep clean urls. So I'm looking for a way to keep it, IF that's possible.

index.html

<head>
<base href="/testing/onetest/">
<script>
 app.controller('masterController',function($location){
     setTimeout(change, 3000);
         function change() {
            console.log("changing in 3 seconds");
            $location.path('/red');
          }
 });
</script>
</head>

<body ng-app="app" ng-controller="masterController">

<a href="/testing/onetest/">Main</a>
<a href="red">Red</a>
<a href="green">Green</a><br>


<div ng-view></div>

</body>

app.js

var app = angular.module("app", ["ngRoute"]);
app.config(function($routeProvider,$locationProvider) {
    $routeProvider
    .when("/", {
        templateUrl : "home.html",
         controller  : 'mainController'
    })
    .when("/red", {
        templateUrl : "red.html"
    })
    .when("/green", {
        templateUrl : "green.html"
    });

    $locationProvider.html5Mode(true);
});

Upvotes: 2

Views: 68

Answers (1)

Siddhesh Phatak
Siddhesh Phatak

Reputation: 198

For angular js version less than 1.6

$window.location.href= '#red';

For angular js version 1.6 or more

$window.location.href= '#!red';

Try this and see if it works. This might help you to change the ng-view from function. It worked for me.

Upvotes: 2

Related Questions