Reputation: 1611
There is a common function in my rootscope. I have more than one controller which is using the same function.
I need to change the Scope variable from Rootscope Function.
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>
Upvotes: 3
Views: 1426
Reputation: 1611
It is possible using this keyword.
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>
Upvotes: 1
Reputation: 16368
Why don't you just call the rootScope function?
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){
}]);
Idieally this would be better if you make a service for this.
myApp.service('DateService', function() {
return {
getDate: function() {
return new Date();
}
};
});
See your updated fiddle
Upvotes: 2
Reputation: 1368
This is probably not possible, since your $rootScope does not have any reference of the scope, neither is it "meant" to do that.
You can inject $rootscope into your controller and bind to it, if that helps.
app.controller('sampleCtrl', function($scope, $rootScope){
$scope.var = $rootScope.var2;
});
Cheers.
Upvotes: 3