从指令访问控制器数组

时间:2018-01-19 15:40:49

标签: angularjs

我想在我的指令中使用范围变量:

app.controller('YEL', ['$scope', '$routeParams', '$http', 'ngMeta', function($scope, $routeParams, $http, ngMeta) {   
    $http.get('xxx').success(function(res) {
        $scope.yels = res; /* Array */

    }).error(function(res, status) {
        ...
    });

}]);

这是我的HTML:

<div ng-repeat="yel in yels">
    <div plangular="{{yel.soundcloud}}" ng-if="yel.soundcloud" >
        <div ng-if="track" id="{{yel.id}}" ng-click="playPause()" title="Play/Pause" ">
            <i ng-if="player.playing !== track.src" class="fa fa-2x fa-play grow" aria-hidden="false"></i>
            <i ng-if="player.playing === track.src" class="fa fa-2x fa-pause grow" aria-hidden="false"></i>
        </div>
    </div>
</div>

这是我的Plangular指令:

plangular.directive('plangular', ['$timeout', 'plangularConfig', function($timeout, plangularConfig) {
  var player = new Player();

  return {

    restrict: 'A',
    scope: true,

    link: function(scope, elem, attr) {
      var src = attr.plangular;
      scope.player = player;
      scope.audio = player.audio;
      scope.track = true;

    ...
      player.audio.addEventListener('ended', function() {
        if (scope.track.src === player.audio.src) {
          scope.next();
        } else { 
            if (scope.repeatclicked) {
                this.play(src);
                console.log(scope.yel.id);

            }               
        }           
      });   
    ...
    }
  }


}]);

有没有办法在我的指令中使用ng-repeat中定义的yel.id?我尝试console.log(scope.yel.id);没有任何成功。

修改

我已经按照@Maak的建议为指令添加了一个属性,我现在正在将yel-id={{yel.id}}传递给指令,但我的console.log(attr.yelId)的输出是{{ yel数组内所有yel的yel.id}},如图所示:

enter image description here

我想只记录单个指令的yelId,类似于console.log(this.attr.yelId);

1 个答案:

答案 0 :(得分:0)

您可以通过更改以下内容将yel对象传递给指令。

yel对象传递给您的指令

<div ng-repeat="yel in yels">
    <div plangular="yel" ng-if="yel.soundcloud" >
       <!-- ... -->
    </div>
</div>

在范围指令

中包含yel对象
plangular.directive('plangular', function($timeout, plangularConfig) {
    return {
        restrict: 'A',
        scope: {
            plangular: '='
        },
        // ...
    }
});

然后您可以使用

访问指令中id对象的yel
link: function(scope, elem, attr) {
  console.log(scope.plangular.id)
}

或者您也可以使用其他自定义属性传递ID。

<div ng-repeat="yel in yels">
    <div plangular="{{yel.soundcloud}}" yel-id={{yel.id}} ng-if="yel.soundcloud" >
       <!-- ... -->
    </div>
</div>

然后使用

访问指令中的该属性
 link: function(scope, elem, attr) {
  console.log(attr.yelId)
}