16

So, I have the following relatively simple Angularjs directive

app.directive('myDirective', function () {
      return {
          restrict: 'E',
          scope: {
              site: '@',
              index: '@'
          },
          template: '<div>{{site}}</div>',
          replace: true,

      }
  });

And here is where I call the directive in HTML

<div id="eventGraphic" class="span12">
    <my-directive ng-repeat="site in IEvent.sites" site="{{site}}" index="{{$index}}"></my-directive>
</div>

Which, given that each site is an object, produces this output (copied from browser)

{"name":"Hurlburt","_id":"5148bb6b79353be406000005","enclaves":[]}
{"name":"Walker Center","_id":"5148cca5436905781a000005","enclaves":[]}
{"name":"test1","_id":"5148ce94436905781a000006","enclaves":[]}
{"name":"JDIF","_id":"5148cf37436905781a000007","enclaves":[]} 

However, if I change the template in the directive to

 template: '<div>{{site.name}}</div>',

it does not produce any output. This seems like a fairly straightforward use case, any ideas what I could be doing wrong? The desired output would be just the name field in each object.

1
  • Is your directive going to allow the user to change the site data, or will it be creating its own properties on the scope? If not, then you probably don't need an isolate scope -- you can save some memory and have the directive use the scope that ng-repeat creates. Commented Mar 20, 2013 at 22:26

1 Answer 1

21

You need to use '=' to map the object. '@' implies you're just passing a string value to the new scope.

app.directive('myDirective', function () {
      return {
          restrict: 'E',
          scope: {
              site: '=', //two-way binding
              index: '@' //just passing an attribute as a string.
          },
          template: '<div>{{site}}</div>',
          replace: true,

      }
  });

Then in your markup, don't use a binding in the attribute, just pass the expression:

<div id="eventGraphic" class="span12">
    <!-- below, site="site" is passing the expression (site) to
         the two way binding for your directive's scope,
         whereas index="{{$index}}" is actually evaluating the expression
         ($index) and passing it as a string to the index attribute,
         which is being put directly into the directive's scope as a string -->
    <my-directive ng-repeat="site in IEvent.sites" 
            site="site" 
            index="{{$index}}"></my-directive>
</div>
Sign up to request clarification or add additional context in comments.

Comments

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.