0

what is the best way to do the following scenario:

In a component I have a function that builds an array like so:

var arr = ['a','b'];

In the parent controller, I want to be able to change this array if needed. I thought that I may use events for this: in PHP (using Laravel) I can call by reference a variable when listening on that event and by doing so, when I modify the variable inside the listen block, the original variable gets updated to.

In angular, i tried to $emit an event on the rootScope and listen on that event on the parent controller:

// directive controller
$rootScope.$emit('$genericColumns', arr)

// parent controller
$rootScope.$on('$genericColumns', function($event, arr) {
        arr = [];
        return arr;
    });

But doing this, does not modify the original arr variable.

What is the best way to accomplish this? How can i modify a variable in the child directive scope when needed?

Filip
  • 346
  • 1
  • 4
  • 15

2 Answers2

0

I'd use a service.

angular.module('app').factory('genericColumns', function(){
  var columns = {};

  columns.arr = [];   

  return columns;
});

Obviously you'll need to reference it properly in your application, I've just used app here.

Then inject it into your controller(s) and they'll share the data.

angular.module('app').controller('ColumnCtrl', function (genericColumns){
  $scope.columns = genericColumns.arr;
});

You can still use the $emit and $on for each controller being made aware of when changes have been made although I'd suggest using an observer pattern for that instead of using $rootScope.

Community
  • 1
  • 1
deadwards
  • 2,109
  • 1
  • 16
  • 27
  • And how exactly would i modify the columns variable? – Filip Aug 18 '16 at 10:35
  • I've updated the answer with a very simple example for you. The `arr` and would be shared between the two but you may still need to track changes made in either, which is why I suggest the observer pattern for that. – deadwards Aug 18 '16 at 10:44
0

I ended up creating a service:

angular.module('common.directives.lists', [])
                .factory('$generic', function() {
                    return {Columns: []};
                })

Then, in both my controllers I injected $generic. In my directive controller i entered my main columns and after that, i broadcasted an event on $rootScope $rootScope.$broadcast('$genericColumns'). After this, i could listen to the $genericColumns event on the parent controller and there I would modify the $generic.Columns array (add additional columns) and the changes would reflect on the directive controller too. Works ok.

Filip
  • 346
  • 1
  • 4
  • 15