ng-repeat中的自定义指令

时间:2017-11-13 21:16:56

标签: javascript angularjs angularjs-directive

我有这个自定义指令。 我在ng-repeat。{/ p>里面打电话给我的指令

  

selectedMealCalc.calculated_foods为'items',是一个对象数组

 <!-- DIRECTIVE -->
    <div ng-repeat="option in [0,1,2,3,4]">
        <meal-option option="{{option}}"
                     items="selectedMealCalc.calculated_foods"
                     selectedmealcalc="selectedMealCalc"></meal-option> </div>
    <!-- DIRECTIVE -->

然后我在angularjs中创建了这个指令。

'use strict';

    angular.module('nutriApp').directive('mealOption', ['$compile', function($compile) {
      return {
        restrict: 'E',
        templateUrl: 'views/checkins/meal-options.html',
        scope: {
          option: "@",
          items: "=",
          selectedmealcalc: "="
        },
        controller: ['$scope', 'Food', function($scope, Food) {
          $scope.sumFood = {};
          $scope.summerizeOption = function(foods) {
            if(foods.length > 0){
               $scope.sumFood = Food.summerize(foods);
            }
            return $scope.sumFood;
          };
        }]
      };
    }]);

这个HTML指令。

<div class="row" ng-init="filteredItems = ( items | filter: { food_option: option } )" ng-controller="CheckinsPlansCtrl">
  <div class="col-md-12" ng-show="filteredItems.length > 0">
    Opção {{ option }}
    <table class="table table-calculo table-striped">
      <thead>
        <tr>
          <th>Alimento</th>
          <th>Quantidade</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <tr ng-repeat="foodCalculation in filteredItems track by $index">
          <td>{{foodCalculation.food.name}}</td>
          <td>{{foodCalculation.gram_amount}} g</td>
        </tr>
      </tbody>
    </table>
  </div>
</div>

当我更新selectedMealCalc.calculated_foods时,自定义指令未更新。 我必须关闭模态并在我的页面中再次打开以查看新行。

1 个答案:

答案 0 :(得分:0)

此帖子中的评论为Custom directive inside ng-repeat。 我删除了MyEnum因为ng-init:“只是为了初始化范围上的属性。我建议不要使用它。”作为另一个答案Does ng-init watch over change on instantiated property like ng-model does?