Angular Change Scope variable from Rootscope function - how to do it?

There is a common function in my cornector. I have several controllers that use the same function.

I need to change the Scope variable from the Rootscope function.

http://jsfiddle.net/qkZHG/

In js

angular.module('myApp', [])
 .run(function($rootScope) {
$rootScope.rs = new Date();

 $rootScope.changeRsFromRs = function() {
  $rootScope.rs = new Date();
};

 //Not Working
 $rootScope.changeSFromRs = function() {
  $scope.s = new Date();
};
})
.controller('myCtrl', function($scope, $rootScope) {
   $scope.s = new Date();

  $scope.changeSFromS = function() {
    $scope.s = new Date();
};

$scope.changeRsFromS = function() {
    $rootScope.rs = new Date();
};
});

In html,

<button class="not-working" ng-click='changeSFromRs()'>Change Scope value from Rootscope</button>
+3
source share
3 answers

Use of this keyword is possible.

http://jsfiddle.net/qkZHG/3/

In JS:

$rootScope.changeSFromRs = function(scope) {
  scope.s = new Date();
};

In HTML:

<button class="not-working" ng-click='changeSFromRs(this)'>Change Scope value from Rootscope</button> 
+1
source

This is probably not possible since your $ rootScope does not have a scope reference, and that does not mean that it is needed.

You can embed $ rootcope in your controller and bind to it if that helps.

app.controller('sampleCtrl', function($scope, $rootScope){
    $scope.var = $rootScope.var2;
});

Greetings.

+3
source

rootScope?

var myApp = angular.module('myApp', []);

myApp.run(function($rootScope) {
    $rootScope.rs = new Date();
    $rootScope.updateDate = function() {
       $rootScope.rs = new Date();
    };
});

myApp.controller('myCtrl', ['$scope', function($scope){
}]);

, , .

myApp.service('DateService', function() {
        return {
            getDate: function() {
                return new Date();
            }
        };
    });

fiddle

+2
source

All Articles