Search code examples
javascriptangularjssymfonyangularjs-scopeangularjs-ng-repeat

AngularJS Create new scope in template?


Using Symfony2.x, I have a twig loop going through data for some data, and I also have an ng-repeat going on for similar elements (difference being these ones get loaded in the background though), but both are to share the same functionality.

I have some odd functionality going on in the twig loop versions that are working perfectly fine in the ng-repeat versions. I have a feeling it's simply a scope issue.

I read in the docs that ng-repeat will automatically create a new scope for the repeated elements, but of course this doesn't happen with a twig loop.

How does one manually, and preferably exclusively IN the template, invoke a new scope per repeated element?


Solution

  • The easiest way might be to add a directive to each element. This can be done in the template. The directive can then request new scope (via scope:true or scope:{}) and each repeated element will get a new scope associated with it.

    You can create a directive on an element like:

    <div mydirective></div>
    

    Then in your code, define the directive:

    myApp.directive('mydirective',function(){
        return {
            scope: true,
            link: function(scope, elem, attrs){
                // do some scope / element stuff here
            }
        }
    });