1

Is it possible to share scope behavior from one of my controllers higher up in my app hierarchy so that it's able to manage data from an unrelated/uninherited scope as a sort of abstract and separate 'remote control'?

This is how I have things setup in psudo-angular:

//Looking to share the ManagedScope1 and ManagedScope2 "changeChannel()" behavior with this controller
<RemoteControlCtrl>
  <ng-click="managedScope1.changeChannel()"></ng-click>
  <ng-click="managedScope2.changeChannel()"></ng-click>
</RemoteControlCtrl>

//ManagedScopes inherit ChangeChannelCtrl scope behaviors
<ChannelChangeCtrl with $scope.changeChannel() method>
  <ManagedScope1></ManagedScope1>
  <ManagedScope2></ManagedScope2>
</ChannelChangeCtrl>

The $scope.changeChannel() method is inherited in both managed scopes, and can act on their own data accordingly.

karthika
  • 4,085
  • 3
  • 21
  • 23
ThinkingInBits
  • 10,792
  • 8
  • 57
  • 82

2 Answers2

0

You need a ChannelService....

.service('ChannelService', function () {
    return {
        changeChannel: function (scopeData, callback) {
             //change the channel

             if (angular.isFunction(callback)) {
                  callback();
             }
        }
    };
});

Usage:

.controller('MyController', ['$scope', 'ChannelService', function ($scope, ChannelService) {
     $scope.dataForChangingChannel = {};
     $scope.changeChannel = function () {
          //do UI stuff here

          ChannelService.changeChannel($scope.dataForChangingChannel, function () {
                //or UI stuff here, after the channel has been changed
          });
     }
}]);
Ben
  • 60,438
  • 111
  • 314
  • 488
0

It would depends on what kind of component that generated the scope.

If it is a completely unrelated scope, you should use $broadcast. You can require $rootScope as dependancies in remote controller and $rootScope.$broadcast('eventName', someData). In your channel controller:

$scope.$on('eventName', function(event, data) {
    // Do something here
})

Another good idea would be using a service, but that would still be hard to call method on another scope. I would say event broadcasting is a nice approach for your problem.

Daiwei
  • 40,666
  • 3
  • 38
  • 48