0

Let's suppose this custom directive mentioned in myHtml.tpl.html:

<my-directive></my-directive>

This directive is initialized with an isolated scope.

Of course, I have a controller behind myHtml.tpl.html.

I want to communicate a computed array from the isolated scope to the controller's scope.

I could have:

<my-directive arrayToCompute="arrayToCompute"></my-directive>

My isolated scope (in directive) being:

scope: {arrayToCompute: "="}

and my controller declaring this initially empty array:

$scope.arrayToCompute = [];

However, it seems pretty.....ugly..

What is a good alternative?
(I'm pointing out that I don't want to remove the scope isolation of the directive).

Mik378
  • 21,881
  • 15
  • 82
  • 180
  • Do you tried $parentScope? – Unrealsolver Aug 13 '14 at 12:15
  • Nope, didn't try it. I found this: http://stackoverflow.com/questions/17900201/how-to-access-parent-scope-from-within-a-custom-directive-with-own-scope-in-an It's not recommended to access a parent scope directly. Especially regarding scope variable names, generic in directive => should be specific in controller. – Mik378 Aug 13 '14 at 12:22

1 Answers1

2

If you want to decouple this very strictly, I'd suggest introducing a notify-callback. E.g:

app.controller('AppCtrl', ['$scope', function ($scope) {
  $scope.raw      = [1, 2, 3];
  $scope.computed = null;

  $scope.setComputed = function setComputed(computed) {
    $scope.computed = computed;
  };
}]);

app.directive('myDirective', function () {
  return {
    restrict: 'E',
    scope: {
      input:     '=?',
      onCompute: '&'
    },
    link: function (scope) {
      function compute(input) {
        return input.slice().reverse();
      }

      scope.$watch('input', function (nv) {
        scope.onCompute({
          computed: compute(nv)
        });
      });
    }
  };
});

with:

<body data-ng-controller="AppCtrl">
  <my-directive input="raw" on-compute="setComputed(computed)"></my-directive>

  <pre>{{ raw | json }}</pre>
  <pre>{{ computed | json }}</pre>
</body>

demo: http://jsbin.com/satavesuhiqu/1/

Yoshi
  • 54,081
  • 14
  • 89
  • 103