Search code examples
javascriptangularjsangularjs-scopeangular-directive

AngularJS: Access value of data binding from within directive


I am trying to access the value a data binding inside a directive executed after an ng-repeat.

Here is my html:

<div ng-repeat="(version, data) in versions" rszvers>
  <div class="hidden_div">{{version}}</div>
  <div><p>{{data.opts.a}}</p></div>
  <div><p>{{data.opts.b}}</p></div>
  <div><p>{{data.opts.c}}</p></div>
</div>

And my directive:

 .directive('rszvers', function() {
  return function(scope, element, attrs) {
    var p = element.find("p").contents();
    angular.forEach(p, function(value, key) {
      console.log(key);
      console.log(value.textContent);
    });
  };
 })

I tried to access the value of my <p> with the value.textContent (which shows the correct value in the console), but of course I only retrieve {{data.opts.a}}. I tried to eval or parse this binding with no luck.

I know there must be an easy way to do this but I cannot wrap my head around this. Can you please shed some light on what I am missing and how to solve this issue?


Solution

  • You can access it via scope e.g:

    .directive('rszvers', function() {
      return function(scope, element, attrs) {
       console.log(scope.data.opts.a, scope.data.opts.b, scope.data.opts.c);
     });