【问题标题】:Custom directive inside ng-repeatng-repeat 中的自定义指令
【发布时间】:2017-11-13 21:16:56
【问题描述】:

我有这个自定义指令。 我在ng-repeat 中调用我的指令,如下所示。

selectedMealCalc.calculated_foods 作为“项目”,是一个对象数组

 <!-- 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 时,自定义指令没有更新。 我必须关闭模式并在我的页面中再次打开才能看到新行。

【问题讨论】:

  • 是的。我认为您的问题是 ng-init stackoverflow.com/questions/25574048/… 尝试使用手表或将 ng-init 逻辑移动到您的控制器
  • 嗨@CharlieNg,你的答案是正确的。解决了我的问题。我确实知道 ng-init 的这种行为。谢谢。
  • 不错!!!!!!!!!!!!

标签: javascript angularjs angularjs-directive


【解决方案1】:

正如这篇文章中的评论Custom directive inside ng-repeat。 我删除了ng-init,因为 ng-init:“仅用于初始化作用域上的属性。我建议不要使用它。”作为另一个答案Does ng-init watch over change on instantiated property like ng-model does?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-26
    • 1970-01-01
    • 1970-01-01
    • 2015-03-06
    • 2013-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多