Read more

AngularJS: Access the scope for a rendered DOM element

Henning Koch
April 28, 2013Software engineer at makandra GmbH

This trick might be useful to implement more complicated directives in AngularJS. I needed it to do drag'n'drop in a hierarchical tree.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

Let's say you have this $scope in your Angular controller:

$scope.tasks = [
  { 'text': 'Task 1' },
  { 'text': 'Task 2' }
]

And you have this template:

<ul ng-repeat="task in tasks">
  <li>
    {{task.text}}
  </li>
</ul>

Which renders this HTML:

<ul>
  <li>Task 1</li>
  <li>Task 2</li>
</ul>

If you'd like to access the scope bound to the second <li> you can say this in jQuery:

var li = $('li:eq(1)');
li.scope().node // => { 'text': 'Task 2' }

Or if you'd like to access the entire list:

li.scope().parent.node // => [{ 'text': 'Task 1' }, { 'text': 'Task 2' }]
Posted by Henning Koch to makandra dev (2013-04-28 14:59)