0

I have a webpage that runs well, but on a certain route, it would not load certain functions. For example, this is code:

myApp.controller('people', ['$scope', function($scope) {

    $scope.$watch('$viewContentLoaded', function(){
        console.log('la 1');

        $scope.allPeople = function() {
            // This does not run when refreshed at https://www.website.com/people
            console.log('la 2');
        }
    })
]);

This has the same behavior, la 1 works, not la 2:

myApp.controller('people', ['$scope', function($scope) {
    console.log('la 1');
    $scope.allPeople = function() {
        console.log('la 2');
    }
}]);

These are routes:

myApp.config(function($routeProvider) {
    $routeProvider
    .when('/', {
        templateUrl: '../../templates/all.html',
        controller: 'all'
    })
    .when('/people', {
        templateUrl: '../../templates/people.html',
        controller: 'people'
    })
});

When I load https://www.website.com, and navigate to People tab, it loads list of people. But, when I load the page WHILE in the People tab, the page would load, but without the list: I see la 1 printed, not la 2.

How can I run the allPeople when refreshed from /people?

4
  • what route module are you using ? show us how you set up the routes. Commented Jun 5, 2017 at 18:25
  • @eranotzap, done Commented Jun 5, 2017 at 18:27
  • ok nothing call allPeople function you only declare it. Commented Jun 5, 2017 at 18:28
  • @eranotzap, how can I call it? Commented Jun 5, 2017 at 18:29

1 Answer 1

1

The reason is that you only declared the function but never execute it.

myApp.controller('people', ['$scope', function($scope) {

     $scope.allPeople = function() {          
          console.log('la 2');
     }

     $scope.$watch('$viewContentLoaded', function(){
         console.log('la 1');        
         $scope.allPeople();
     });   
]);

Additionally don't declare it every time you route. And don't forget to unregister the watch (thanks @NainishModi).

   myApp.controller('people', ['$scope', function($scope) {

     $scope.allPeople = $scope.allPeople || function() {          
          console.log('la 2');
     }

     var deReg = $scope.$watch('$viewContentLoaded', function(){
         console.log('la 1');        
         $scope.allPeople();
     })

      //deRegister watch
      $scope.$on('$destroy', deReg);
]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.