Question

I'm trying to change view from the controller but it isn't working.

app.js

var app = angular.module('vla', ['ngRoute']);
app.config(function ($routeProvider){
           $routeProvider
            .when('/view1',
                  {
                  controller: 'loginController',
                  templateUrl: 'partials/loginView.html'
                  })
           .when('/view2',
                 {
                 controller: 'noteController',
                 templateUrl: 'partials/videoView.html'
                 })
           .when('/view3',
                 {
                 controller: 'videoListController',
                 templateUrl: 'partials/videoListView.html'
                 })
           .otherwise({ redirectTo: '/view1' });
});

view: videoListView.html

<div class="video" data-ng-click="selectVideo(video)" ng-repeat="video in videos">
        <div ng-repeat="(key, val) in video|orderBy:orderByField:videoName">

            {{key}}: {{val}} </br>

        </div>
</div>

controller.js

app.controller('videoListController', function($scope,getVideoListService){

           $scope.selectVideo = function(video){
           $location.url('/view2');
           }
});

I have tried the following but none seem to work

$location.url('#/view2');
$location.url('/view2');
$location.path('/view2');
$location.path('#/view2');

When inserting a link on a view page such as

<a href="#/view2"</a>click

the page is correctly routed, would appreciate any help on changing views from the controller.

Thanks in advance

Was it helpful?

Solution

UPDATE:

I should have seen this before, but $location is a service you aren't passing in.

//Need to pass in $location
app.controller('videoListController', function($scope, $location, getVideoListService){

   $scope.selectVideo = function(video){
      $location.url('/view2');
   }
});

To help you out in furthering your Angular-foo, I would take a look at John Lindquist's fantastic videos at egghead.io. Most of the Angular videos are free to watch.

Aside from that, the Dependency Injection section from the official Angular Developers Guide is going to be a good read.


Based on what you are describing, my guess is that your function isn't being called at all. Try adding some console output to see if it get's called, and then working to fix your issues.

$scope.selectVideo = function(video){

    console.log('Changing the route...');

    $location.path('/view2');
}

Check the console output for errors by opening up the developer tools.

OTHER TIPS

Try the following instead

$window.location = "/view2";

or on click of a button which in turn uses a function:

$scope.randomFunctionAppears= function() {

    $window.location = "/view2";

};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top