Search code examples
angularjsangularjs-directivewatchbindonce

Pass object to custom directive without creating watchers?


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


Solution

  • 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