Search code examples
angularjsangularjs-scopeangularjs-service

$scope variable isn't recognized when calling initialization function


I have the following code, where I want to receive all the texts from the current user and show them on screen when the page loads:

angular.module('eddieApp')
    .controller('MainController', function ($scope, Principal, TextService) {

        $scope.texts = [];

        Principal.identity().then(function(account) {
            $scope.account = account;
            $scope.isAuthenticated = Principal.isAuthenticated;
        });

        $scope.findByUser = function(){
            TextService.findByUser($scope.account.login).success(function(data){
                $scope.texts = data;
            });
        };

        // receive all notes from current user
        $scope.$watch(function(scope) { return scope.account; },
                      function()      { $scope.findByUser(); });


    });

The problems is that it works, but I don't understand why is this the only method to make it work.

I tried to call the function $scope.findByUser() like this:

angular.module('eddieApp')
    .controller('MainController', function ($scope, Principal, TextService) {

    $scope.texts = [];

    Principal.identity().then(function(account) {
        $scope.account = account;
        $scope.isAuthenticated = Principal.isAuthenticated;
    });

    $scope.findByUser = function(){
        TextService.findByUser($scope.account.login).success(function(data){
            $scope.texts = data;
        });
    };

    $scope.findByUser();

});

but I get an error saying that $scope.account.login isn't recognized.

Also, I tried to put the directive ng-init="findByUser()" in my html code, but again, I get the same error saying that $scope.account.login isn't recognized.

Finally i made it work with the $watch function, but I don't understand why the first two methods didn't work, because they are easier to understand and I would preffer using them instead of $watch.


Solution

  • It works because your $watch ensures that $scope.account is defined before running $scope.findByUser.

    In your example without the watch, findByUser executes immediately, and tries to use the login property of $scope.account which is undefined.

    If having a user account is a prerequisite of findByUser, and there's nothing in your view that calls it immediately, it may make more sense to call findByUser in your then block, which would avoid the need for a $watch.