如何在AngularJS指令中获取ng-repeat中的yel.id变量?
Fixing Access to
yel.id in the Plangular Directive Hey there, let's get this sorted out—you're right that accessing scope.yel.id directly isn't working, and the attribute approach you tried had an issue with closure retention. Here's how to properly pass and access the current yel.id in your plangular directive:
Step 1: Update the HTML to Bind the ID Correctly
First, modify your ng-repeat template to pass the yel.id directly to the directive without interpolation (this avoids string parsing issues and ensures proper binding):
<div ng-repeat="yel in yels"> <div plangular="{{yel.soundcloud}}" yel-id="yel.id" 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>
Step 2: Modify the Directive to Accept the Bound ID
Update your directive's scope configuration to explicitly bind the yel-id attribute, and fix the closure issue in the ended event listener:
plangular.directive('plangular', ['$timeout', 'plangularConfig', function($timeout, plangularConfig) { var player = new Player(); return { restrict: 'A', // Use an object scope to explicitly bind required properties scope: { plangular: '@', // Get the SoundCloud URL as a string yelId: '=' // Two-way bind the current yel's ID }, link: function(scope, elem, attr) { var src = scope.plangular; // Save the current ID to avoid closure-related value overwrites var currentYelId = scope.yelId; 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); // Use the saved current ID (or scope.yelId for real-time access) console.log(currentYelId); } } // Trigger Angular's digest cycle since this event runs outside Angular scope.$apply(); }); ... } } }]);
Why This Works
- Explicit Scope Binding: Using
scope: { yelId: '=' }creates a direct binding between the directive's scope and theyel.idfrom theng-repeatitem. No more guessing about scope inheritance! - Closure Fix: Saving
currentYelIdin the link function ensures each directive instance retains its own ID value—this prevents all event listeners from referencing the lastyelitem's ID (a common closure pitfall). - Digest Cycle Trigger: The
scope.$apply()call tells Angular to sync the scope with the view, since theendedevent fires outside Angular's context.
内容的提问来源于stack exchange,提问作者LucaP
相关产品推荐
相关产品推荐

