将范围变量传递给指令

时间:2015-05-15 00:14:40

标签: angularjs angularjs-directive

我可以在console.log中看到我的数据,我只是不明白为什么我无法使用$scope.$parent.locations访问它。我错过了什么?

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("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};
})

1 个答案:

答案 0 :(得分:1)

这是因为$attr.couponsRepeater未定义,因为attr.couponsRepeater具有您要查找的值。

另一方面,使用$parent访问数据并不是一个好主意,您的指令应该使用隔离范围,父级应该通过其他属性将数据传递给它。 Example JSFiddle here

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

使用HTML。

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