Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$rootScope is not working with me in AngularJs

I get the value of my $rootScope inside my function But I wanna get thsi value inside all the functions of my Controller to passe it to another controller: Can You Help me please

MY HTML:

<input type="checkbox"   ng-model="u.selected" data-ng-click="consoleClient(u)">

my Script Code :

$scope.client = {
    id : null,
    nom : '',
    nberPhone : '',
    adresse : '',
    selected : false
};

$scope.consoleClient = function(client) {
    $rootScope.test = client;

    console.log(" lll "+$rootScope.test);
};
console.log(" aaaa "+$rootScope.test);

The console log is returning the correct result But the second Out of the function Is returning undefined. Can you explain the reason for me please.

like image 669
yeddez Avatar asked Mar 13 '23 17:03

yeddez


1 Answers

Yes, because you haven't call to $scope.consoleClient so it's not defined outside the function scope. It will work after you call the function:

$scope.consoleClient = function(client) {
    $rootScope.test = client;

        console.log(" lll "+$rootScope.test);
};
$scope.consoleClient('clientName');
console.log(" aaaa "+$rootScope.test); // output: ' aaaa clientName'

If you want to watch for changes of the variable outside the function, you can do the following:

$scope.$watch(function() {
    return $rootScope.test;
}, function(newValue, oldValue) {
    console.log('Old value: ', oldValue);
    console.log('New value: ', newValue);
}, true); // Note the "true" - Compare the object using "angular.equal"
like image 77
Alon Eitan Avatar answered Mar 15 '23 05:03

Alon Eitan