Servicenow portal

kali
Tera Contributor

Hi ,

Please explain the $scope.on and $scope.destory in servicenow portal

Thanks in advance.

 

 

1 ACCEPTED SOLUTION

@kali 

My apologies I misread your message I thought you were asking for a simple code for $scope.on and destroy. 

I added a $scope.broadcast to the previous code to show how it works. 

        $scope.broadcastCustomEvent = function() {
            var eventData = { message: 'This is a custom event!' };
            $scope.$broadcast('custom.event', eventData);
            console.log('Custom event broadcasted with data:', eventData);
        };

        // Listen for a custom event
        $scope.$on('custom.event', function(event, data) {
            console.log('Custom event received with data:', data);
            // Handle the event
        });

        // Clean up when the scope is destroyed
        $scope.$on('$destroy', function() {
            console.log('Widget scope is being destroyed, cleaning up...');
            // Perform cleanup actions
        });
    }

 

View solution in original post

6 REPLIES 6

@kali 

My apologies I misread your message I thought you were asking for a simple code for $scope.on and destroy. 

I added a $scope.broadcast to the previous code to show how it works. 

        $scope.broadcastCustomEvent = function() {
            var eventData = { message: 'This is a custom event!' };
            $scope.$broadcast('custom.event', eventData);
            console.log('Custom event broadcasted with data:', eventData);
        };

        // Listen for a custom event
        $scope.$on('custom.event', function(event, data) {
            console.log('Custom event received with data:', data);
            // Handle the event
        });

        // Clean up when the scope is destroyed
        $scope.$on('$destroy', function() {
            console.log('Widget scope is being destroyed, cleaning up...');
            // Perform cleanup actions
        });
    }

 

Dan Essigmann
Tera Expert

Hey Kali,
So they are both going to be AngularJS methods that are just used to handle event listeners in widgets. 
$scope.on is listening for events that are broadcasted from other components within the same widget, if the event happens then the callback function will be executed.

$scope.destroy is something that you can use to mitigate memory leaks just to make sure that the resources are properly disposed of. 

I guess a real world use case of both of them together would be something like having $scope.on listen for a custom event and then create a message. Then when the user navigates away from the widget $scope.destroy could just clean up that last message.

Hope this helps!