0

I have a problem with passing object information to my custom directive, which has an isolate scope. I have boiled my problem down to this simple plnkr to demonstrate the wall I am hitting:

http://plnkr.co/edit/oqRa5pU9kqvOLrMWQx1u

Am I just using ng-repeat and directives incorrectly? Again, my goal is to pass the object information from the ng-repeat loop into my directive which will have its own scope.

HTML

<body ng-controller="MainCtrl">
    <ul>
      <li ng-repeat="i in items", my-directive="i">
        <span>{{$index}}</span>
        <p>{{item.name}}</p>
        <p>{{item.value}}</p>
      </li>
    </ul>
  </body>

JS

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.items = [
      {name: "Name #1", value: "Value #1"},
      {name: "Name #2", value: "Value #2"},
      {name: "Name #3", value: "Value #3"}
    ];
});

app.directive('myDirective', function($scope) {
  return {
    restrict: "A",
    scope: { item: "=myDirective" },
    link: function(scope, elem, attrs) {

    }
  }
});

Thank you.

1 Answer 1

1

Issues:

  • remove $scope from directive function
  • remove comma from HTML after ng-repeat

Provide element with new attribute, for example value but my-directive="i" will work as well.

HTML

 <ul>
      <li ng-repeat="i in items" my-directive value="i">
        <span>{{$index}}</span>
        <p>{{item.name}}</p>
        <p>{{item.value}}</p>
      </li>
    </ul>

JS

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.items = [
      {name: "Name #1", value: "Value #1"},
      {name: "Name #2", value: "Value #2"},
      {name: "Name #3", value: "Value #3"}
    ];
});

app.directive('myDirective', function() {
  return {
    restrict: "A",
    scope: { item: "=value" },
    link: function(scope, elem, attrs) {
      console.log(scope.item);
    }
  }
});

Demo Plunker

Sign up to request clarification or add additional context in comments.

1 Comment

Do you know why it is necessary to have to create a new attribute and assign it to that? It would be neater if I could pass it directly to the name of the directive.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.