Quentin F
Quentin F

Reputation: 738

How to pass the result of a function call to a directive?

I declared a function on my scope that return an object. I try to pass the result of this function to a custom directive, but it triggers an infinite digest loop (open your console and run the snippet).

It seems that the objectEquality flag is not set on the watcher and that's why angular is not performing a deep comparison.

What am I doing wrong ? Is it even possible to achieve or am I going against Angular principles ?

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.bar = function() {
    return {
      baz: 'qux'
    };
  };
}).directive('myDirective', function() {
  return {
    restrict: 'E',
    scope: {
      foo: '='
    }
  }
});
<script src="https://code.angularjs.org/1.3.16/angular.js"></script>

<div ng-app="plunker">
  <div ng-controller="MainCtrl">
    <my-directive foo="bar()"></my-directive>
  </div>
</div>

Upvotes: 0

Views: 395

Answers (2)

ReeganLourduraj
ReeganLourduraj

Reputation: 873

When you pass your scope through function you have to use '&'

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.bar = function() {
    return {
      baz: 'qux'
    };
  };
}).directive('myDirective', function() {
  return {
    restrict: 'E',
    scope: {
      foo: '&'
    }
  }
});
<script src="https://code.angularjs.org/1.3.16/angular.js"></script>

<div ng-app="plunker">
  <div ng-controller="MainCtrl">
    <my-directive foo="bar()"></my-directive>
  </div>
</div>

Upvotes: 1

Nicholas Thomson
Nicholas Thomson

Reputation: 548

Try using one-way binding (&) instead. That will attach a getter function to your directive scope, you can use that function to get the result of the bar function.

See below:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.bar = function() {
    return {
      baz: 'qux'
    };
  };
}).directive('myDirective', function() {
  return {
    restrict: 'E',
    scope: {
      foo: '&'
    },
    link: function(scope){
      console.log(scope.foo())
    }
  }
});
<script src="https://code.angularjs.org/1.3.16/angular.js"></script>

<div ng-app="plunker">
  <div ng-controller="MainCtrl">
    <my-directive foo="bar()"></my-directive>
  </div>
</div>

Upvotes: 1

Related Questions