0

How might one go about passing an object to Angular's (Angular 1.4.8) & ampersand scope binding directive?

I understand from the docs that there is a key-destructuring of sorts that needs named params in the callback function, and the parent scope uses these names as args. This SO answer gives a helpful example of the expected & functionality. I can get this to work when explicitly naming the params on the parent controller function call.

However, I am using the & to execute actions via a factory. The parent controller knows nothing of the params and simply hands the callback params to a dataFactory, which needs varied keys / values based on the action.

Once the promise resolves on the factory, the parent scope updates with the returned data.

As such, I need an object with n number of key / value pairs, rather than named parameters, as it will vary based on each configured action. Is this possible?

The closest I have seen is to inject $parse into the link function, which does not answer my question but is the sort of work-around that I am looking for. This unanswered question sounds exactly like what I need.

Also, I am trying to avoid encoding/decoding JSON, and I would like to avoid broadcast as well if possible. Code stripped down for brevity. Thanks...

Relevant Child Directive Code

function featureAction(){
    return {
        scope: true,
        bindToController: {
            actionConfig: "=",
            actionName: "=",
            callAction: "&"
        },
        restrict: 'EA',
        controllerAs: "vm",
        link: updateButtonParams,
        controller: FeatureActionController
    };
}

Child handler on the DOM

 /***** navItem is from an ng-repeat, 
        which is where the variable configuration params come from *****/

ng-click="vm.takeAction(navItem)"

Relevant Child Controller

function FeatureActionController(modalService){
    var vm = this;
    vm.takeAction = takeAction;

    function _callAction(params){
        var obj = params || {};
        vm.callAction({params: obj});  // BROKEN HERE --> TRYING
                                       //TO SEND OBJ PARAMS
    }

    function executeOnUserConfirmation(func, config){
    return vm.userConfirmation().result.then(function(response){ func(response, config); }, logDismissal);
}

function generateTasks(resp, params){
    params.example_param_1 = vm.add_example_param_to_decorate_here;
    _callAction(params);
}

function takeAction(params){
    var func = generateTasks; 
    executeOnUserConfirmation(func, params);
}

Relevent Parent Controller

function callAction(params){
        // logs undefined -- works if I switch to naming params as strings
        console.log("INCOMING PARAMS FROM CHILD CONTROLLER", params) 
        executeAction(params);   
    }

    function executeAction(params){
        dataService.executeAction(params).then(function(data){ 
            updateRecordsDisplay(data); });
    }
nrako
  • 2,952
  • 17
  • 30

1 Answers1

1

I think the example below should give you enough of a start to figure out your question:

<!DOCTYPE html>
<html ng-app="myApp">
  <head>
    <meta charset="utf-8">
    <title>Angular Callback</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <script>
    var myApp = angular.module("myApp", []);

    myApp.controller('appController', function($scope) {
      $scope.var1 = 1;

      $scope.handleAction1 = function(params) {
        console.log('handleAction1 ------------------------------');
        console.log('params', params);
      }

      $scope.handleAction2 = function(params, val1) {
        console.log('handleAction2 ------------------------------');
        console.log('params', params);
        console.log('val1', val1);
      }

    });


    myApp.controller('innerController', innerController);
    innerController.$inject = ['$scope'];
    function innerController($scope) {
      $scope.doSomething = doSomething;

      function doSomething() {
        console.log('doSomething()');
        var obj = {a:1,b:2,c:3}; // <-- Build your params here
        $scope.callAction({val1: 1, params: obj});
      }
    }

    myApp.directive('inner', innerDirective );
    function innerDirective() {
      return {
        'restrict': 'E',
        'template': '{{label}}: <button ng-click="doSomething()">Do Something</button><br/>',
        'controller': 'innerController',
        'scope': {
          callAction: '&',
          label: '@'
        }
      };
    }
    </script>
  </head>
  <body ng-controller="appController">
    <inner label="One Param" call-action="handleAction1(params)"></inner>
    <inner label="Two Params" call-action="handleAction2(params, val)"></inner>
  </body>
</html>

In the appController I have two functions that will be called by the inner directive. The directive is expecting the outer controller to pass in those functions using the call-action attribute on the <inner> tag.

When you click on the button within the inner directive it called the function $scope.doSomething This, in turn calls to the outer controller function handleAction1 or handleAction2. It also passes a set of parameters val1 and params:

$scope.callAction({val1: 1, params: obj});

In your template you specify which of those parameters you want to be passed into your outer controller function:

call-action="handleAction1(params)"

or

call-action="handleAction2(params, val)"

Angular then uses those parameter names to look into the object you sent when you called $scope.callAction.

If you need other parameters passed into the outer controller function then just add then into the object defined in the call to $scope.callAction. In your case you would want to put more content into the object you pass in:

var obj = {a:1,b:2,c:3}; // <-- Build your params here

Make that fit your need and then in your outer controller you would take in params and it would be a copy of the object defined just above this paragraph.

It this is not what you were asking, let me know.

Intervalia
  • 10,248
  • 2
  • 30
  • 60
  • This looks like it is on the right track. Will get back to you momentarily. Thanks for the note. – nrako Nov 07 '17 at 18:25
  • In short, adding an object to a named key works - `callAction({params: built_up_obj_params})`. I'm not sure where my error was, but it looks to be in working order now. Thanks! – nrako Nov 07 '17 at 18:42