You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中使用$index循环绑定my-grid options属性问题求助

Solution for Dynamic AngularJS Directive Binding

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 to all.Options0 when $index is 0, and all.Options1 when $index is 1.
  • This passes the actual object reference to the options attribute, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:00:22