Pass object to custom directive without creating watchers?

1.4k Views Asked by At

I have created a custom directive ("reusable component") which creates an isolated scope by binding to two objects passed to it via HTML-parameters. A problem with this quickly arises as I have up to 600 of these components in my document, which leads to 1200 watchers and poor performance. I do not need these watchers, just some form of "bind once"-functionality when passing the objects. Is there a way to accomplish this (or a workaround), or do I need to redesign my code?

(Passing data as one or several strings, instead of an object, is a much undesireable option.)

2

There are 2 best solutions below

0
On BEST ANSWER

You should use one-way binding:

scope : {
    myField: '&'
    ....
}

and in directive using:

<my-directive my-field="::myDataObjectFromScope"></my-directive>

Maybe this will help

But if values are constantly at all, you should use service to separate your data from the business logic

2
On

You can evaluate object manually without employing Angular directive scope bindings. Say you have a directive some-component and you want to pass a config object in it preserving isolated directive scope. You could do something like this:

<some-component config="controller.config"></some-component>

Then the directive could look like this:

.directive('someComponent', function() {
  return {
    scope: {
      // some bindings, but not config
    },
    link: function(scope, element, attrs) {
      var config = scope.$parent.$eval(attrs.config)
      console.log(config)
    }
  }
})

$parent is necessary here because directive scope is isolated and you want to get an object defined in outer (parent) scope.

Try it and see if it makes a difference for your set up.