Angular中使用$index循环绑定my-grid options属性问题求助
The issue with your current code is that using interpolation ({{ }}) passes a string (like "all.Options0") to your my-grid directive instead of the actual object reference. AngularJS can’t resolve that string to the all.Options0 object inside the directive. Here’s how to fix it:
Fix 1: Use Bracket Notation for Dynamic Property Access
Replace your interpolated string with Angular’s bracket notation to directly access the dynamic property on the all object:
<div ng-repeat="n in [].constructor(2) track by $index"> {{$index}} <br> <my-grid options="all['Options' + $index]" class="grid"></my-grid> <br> <br> </div>
Why this works:
all['Options' + $index]evaluates toall.Options0when$indexis 0, andall.Options1when$indexis 1.- This passes the actual object reference to the
optionsattribute, which your directive can use directly (assuming it’s set up to accept an object via=or<binding in its definition).
Fix 2: Preparing an Options Array (Cleaner Approach)
For better readability and maintainability, create an array of your options objects in your controller first:
// In your Angular controller $scope.all.optionsArray = [ $scope.all.Options0, $scope.all.Options1 ];
Then loop over this array in your template:
<div ng-repeat="option in all.optionsArray track by $index"> {{$index}} <br> <my-grid options="option" class="grid"></my-grid> <br> <br> </div>
This approach avoids dynamic property name construction in the template and makes your code easier to debug and extend (e.g., just add new options to the array later).
Verify Your Directive’s Binding
Ensure your my-grid directive is set up to accept the options attribute correctly. For example:
angular.module('yourApp').directive('myGrid', function() { return { scope: { options: '<' // One-way binding (recommended for objects) // Or options: '=' for two-way binding if needed }, // Rest of your directive logic }; });
内容的提问来源于stack exchange,提问作者developer

