4

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.)

Vestling
  • 43
  • 1
  • 7
  • The alternatives to two-way binding are documented in [AngularJS Comprehensive Directive API - scope](https://docs.angularjs.org/api/ng/service/$compile#-scope-). – georgeawg Mar 06 '16 at 21:19

2 Answers2

3

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

Boris Parnikel
  • 863
  • 1
  • 7
  • 15
2

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.

dfsq
  • 191,768
  • 25
  • 236
  • 258
  • This does what was requested, but the accepted answer has the advantage of working even when ng-repeating (not being able to pull the objects from parent scope). – Vestling Mar 06 '16 at 21:51
  • Yes, indeed, of course. I totally forgot about one-time binding. – dfsq Mar 06 '16 at 21:56