1

I've made 2 controllers, one for the actual page and one for a success modal. I am broadcasting an even from the modal controller and listening to the even in the page controller. I'm using 'this' to refer to the current instance of the scope variable. But in the $on listener, whenever I try to use the scope variable, it is found null and due to this I cannot modify the page controller variables.

On page controller:

 $rootScope.$on('backToFetch', function() {
            for(var i=0; i < this.fetchUploader.documentData.length; i++) {
                this.fetchUploader.documentData[i].isSuccess = false;
                this.fetchUploader.progress = 0;
            }
            deleteFormFields()
        });

On modal controller:

$rootScope.$broadcast('backToFetch');

How can I get the reference of the scope variable inside the $on listener

Dalorzo
  • 19,834
  • 7
  • 55
  • 102
Ashish Dwivedi
  • 149
  • 2
  • 11
  • what scope? There can be tons of scope in an application – Dalorzo Mar 29 '16 at 12:35
  • Why use `this` and not `$scope` if that's what you're trying to achieve? – Nicklas Nygren Mar 29 '16 at 12:38
  • Generally you would send data to your event. So `$rootScope.$broadcast('backToFetch', 'Some extra data');` and in your handler receive that data: `$rootScope.$on('backToFetch', function(e, data) {});` The data can be anything. Also what is the hierachy between your controllers, you may not need to pollute the `$rootScope`. – ste2425 Mar 29 '16 at 12:38

1 Answers1

0

You can copy scope state to event arguments, like this:

$rootScope.$broadcast('backToFetch', {
     scope: angular.extend($scope, {})
});

And you can now read it's value like so:

$rootScope.$on('backToFetch', function(event, args) {
    console.log(args.scope);
});

This will not modify your source controller scope. As one controller should not directly modify scope of another controller, such operation should be performed by the use of events.

Secondly you should copy only those arguments from scope, that you need, copying whole scope may be a overkill -bad practise.

Community
  • 1
  • 1
Beri
  • 11,470
  • 4
  • 35
  • 57
  • The way you've suggested, helps modify the values in the broadcasting controller, but I need to modify the values of the controller which is listening this broadcast. The scope is found null inside the listener. – Ashish Dwivedi Mar 29 '16 at 13:17
  • So why not send another event from your listener, that will be caught by source controller? You can find more on this subject here: http://stackoverflow.com/questions/28806321/angularjs-can-i-change-scope-value-of-a-controller-from-another-controller – Beri Mar 29 '16 at 13:20