Honus Wagner
Honus Wagner

Reputation: 2908

Angularjs compile a directive inside ng-repeat with isolated scope

I have a directive in the form of a dropdown, pretty simple. The user can click a button to add as many as they need to in a ul, make their selections, and save it off. This is all inside of several ng-repeats.

I'm having trouble mastering the scope. As I expected, this works:

<div ng-repeat="group in groups" question-group="group" class="question-group">
  <div ng-repeat="question in questions">
    <ul>
      <li ng-repeat="case in question.cases"></li>
      <li><new-case group='group'></new-case></li>
    </ul>
  </div>
</div>

When I say "works", I mean that group is properly scoped (the data of the entire group is necessary for the resulting input).

When I switch it to "click to add":

<div ng-repeat="group in groups" question-group="group" class="question-group">
  <div ng-repeat="question in questions">
    <ul>
      <li ng-repeat="case in question.cases"></li>
      <li><a href="#" ng-click="createNewCase($event)">add case</a></li>
    </ul>
  </div>
</div>

group is undefined in the scope. Here is my createNewCase function:

function createNewCase($event) {
  var thisLi = angular.element($event.target).closest('li');
  var listItem = $compile('<li><new-case group=\'group\'></new-case></li>');
  var html = listItem($scope);
  thisLi.before(html);
}
$scope.createNewCase = createNewCase;

And the newCase directive:

angular.module('groups.directives.newCaseDirective', [])
    .directive('newCase', ['$window', function() {
        return {
          restrict: 'EA',
          scope: { group: '=' },
          templateUrl: 'groups/views/newcase.tpl.html'
        };
      }]);

I've been reading for days and I've tried a few other derivatives but I'm ultimately just not getting it. Help is greatly appreciated.

Thanks!

Upvotes: 1

Views: 803

Answers (1)

charlietfl
charlietfl

Reputation: 171679

The issue is that group is created by ng-repeat and is only available in child scopes of ng-repeat.

Each repeated element is in it's own child scope. So your directive version works but your other one doesn't because the controller doesn't see those child scopes.

You would have to pass group as argument of the function if you want to access it in controller

<a href="#" ng-click="createNewCase($event, group)">

Upvotes: 1

Related Questions