嵌套的ng-repeat与模型绑定

时间:2015-07-19 13:47:55

标签: javascript angularjs angularjs-ng-repeat

HTML:

<div class="panel panel-default" ng-repeat="(section, sectionData) in report">
  <div class="panel-heading">{{sectionData.text}}</div>
    <div class="panel-body">
       <div class="row" ng-repeat="(part, partData) in sectionData.attr">
          <div class="col-md-2">
             <label>{{partData.text}}</label>                            
          </div>
          <div class="col-md-10">
            <div class="form-group">                        
              <div class="radio-inline" ng-repeat="condition in radioValues">
                <label class="radio-inline">
                   <input type="radio" name="{{section}}-{{part}}" ng-value="{{condition.value}}" ng-model="partData[model]">
                    {{condition.text}}
                 </label>
               </div>                                
             </div>                            
           </div>
        </div>
     </div>
 </div>

JS模型:

$scope.radioValues = [{
    text: 'Good',
    value: '1'
}, {
    text: 'Average',
    value: '2'
}, {
    text: 'Needs Improvement',
    value: '3'
}];

$scope.report = {
card: {
    text: 'Card',
    attr: {
        front: {
            text: 'Front',
            model: 'detail.report.card.front',
        },
        rear: {
            text: 'Rear',
            model: 'detail.report.card.front.rear'
        },
        assembly: {
            text: 'Assembly',
            model: 'detail.report.card.front.assembly'
        }
    }
} //, and a lot of others like card
};

// Instantiate the model so that values are preselected
for (var section in $scope.report) {
    for (var part in $scope.report[section].attr) {
        initModel($scope.report[section].attr[part]); // basically sets the model values defined in $scope.report to 1
    }
}

$ scope.report对象用于创建html,我试图将html中的ng-model值设置为$ scope.report中定义的字符串。除此之外,我还尝试设置每组无线电的默认值。

ng-model =&#34; partData [model]&#34;部分正确?在控制器中设置模型值后,页面加载时不会预先选择无线电。 $ scope.report中定义的模型应直接绑定到$ scope。例如。 detail.report.card.front.assembly实际上应该变成$ scope.detail.report ...

如何使这项工作?它是正确使用角度?更好的选择?

1 个答案:

答案 0 :(得分:0)

我能够使用具有隔离范围的指令完成此操作。

基本上,我将html转换为名为report的模板。我稍微更改了模板html。这是更改后的代码:

<div class="radio-inline" ng-repeat="condition in radioValues">
  <label class="radio-inline">
    <input type="radio" name="{{section}}-{{part}}" ng-value="{{condition.value}}" ng-model="detail.report[section][part]">
    {{condition.text}}
  </label>
</div>   

然后创建一个如此指令:

app.module('').directive('rating', function(){
   return {
       scope : {
          report: "=",
          detail: "=",
          radios: "="
       },
       restrict : 'E',
       templateUrl : '../view/rating.html',
       link : function($scope, iElm, iAttrs, controller) {}
   };

});

在html中我只是打电话:

<rating report="report" radios="radios" detail="detail"></rating>

因此,我可以通过将其传递给模板来访问父作用域中的detail对象。这允许我直接修改父范围的模型。