Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - understanding scopes

I'm confused, I have this module which routes to different controllers:

var mainModule = angular.module('lpConnect', []).
    config(['$routeProvider', function ($routeProvider) {
    $routeProvider.
        when('/home', {template:'views/home.html', controller:HomeCtrl}).
        when('/admin', {template:'views/admin.html', controller:AdminCtrl}).
        when('/connect', {template:'views/fb_connect.html', controller:MainAppCtrl}).
        otherwise({redirectTo:'/connect'});
}]);

and a Common service like so:

mainModule.factory('Common', ['$rootScope', '$http', function (scope, http) {
        var methods = {
            changeLanguage:function (langID) {
                http.get('JSON/langs/' + langID + '/captions.json').success(function (data) {
                    scope.lang = data;
                });
            },
            initChat:function () {
                console.log(scope); // full object
                console.log(scope.settings); // undefined
            }
        };

        //initiate
        http.get('JSON/settings/settings.json').success(function (data) {
            scope.settings = data;
            methods.changeLanguage(scope.settings.lang);
        });


        return methods;
    }]);

the app loads and gets (through XHR) the settings object, and I can see the settings reflects in my DOM. (captions for example)

Now when I call the initChat method from my HomeCtrl I get an undefined value when trying to access the scope.settings property ... what's strange is that when I log the scope I can see the settings object ... What am I missing?

enter image description here

Update: I found out that what I'm doing wrong is calling my method directly from the controller body:

function HomeCtrl($scope, $location, Common) {
...
Common.initChat()
...
}

if I change the call to be triggered by a click all works fine, but I do need this code to run when the page loads, What is the right approach?

like image 988
Shlomi Schwartz Avatar asked Mar 15 '26 13:03

Shlomi Schwartz


1 Answers

It's a simple problem, I think: You're calling initChat in your scope before the $http call retrieves scope.settings.

like image 50
Andrew Joslin Avatar answered Mar 17 '26 02:03

Andrew Joslin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!