Jacksonkr
Jacksonkr

Reputation: 32207

Passing a scope variable to a directive

I can see my data in the console.log I just don't understand why I can't access it with $scope.$parent.locations. What am I missing?

coupons.html

<div id="coupons-grid" coupons-repeater="locations">
</div>

<!-- <p> When uncommented, below I can see all my location data <p> 
<p> {{ locations }} </p> -->

directive

.directive("couponsRepeater", function() {
  return {
    compile: function(elem, attr) {
      return function($scope, $element, $attr) {
        console.log($scope.$parent); // in the console I see "locations" which is the data I need
        console.log($scope.$parent[$attr.couponsRepeater]); // comes back undefined - this is the call I would like to use because it's dynamic
        console.log($scope.$parent.locations); // comes back undefined
      }
    }
  }
})

CouponsCtrl

.controller('CouponsCtrl', function ($scope, $state, $http, $ionicLoading, userService) {
    $scope.locations = {one:1, two:2, three:3};
})

Upvotes: 0

Views: 712

Answers (1)

Darren Reid
Darren Reid

Reputation: 2322

It's because $attr.couponsRepeater is undefined where as attr.couponsRepeater has the value you are looking for.

On a side note, using $parent to access data is not a good idea, your directive should be using an isolated scope and the parent should pass data to it via other attributes. Example JSFiddle here.

app.directive("couponsRepeater", function() {
  return {
      restrict: 'A',
      scope: {
          locations: '=couponsRepeater'
      },
      link:function (scope, ele, attrs) { 
          console.log(scope.locations);
      }
  }
});

With the HTML.

<div coupons-repeater="locations">
</div>

Upvotes: 1

Related Questions