AngularJS: Access the scope for a rendered DOM element

Posted . Visible to the public.

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

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' }]
Henning Koch
Last edit
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2013-04-28 12:59)