无法在自定义指令内调用函数。范围不是我想要使用的

时间:2017-11-14 19:16:15

标签: angularjs angularjs-directive angularjs-scope

我以前在我的html'computing-td-plan.html'

中有这个
<tr ng-repeat="foodCalculation in selectedMealCalc.calculated_foods">
          <td>{{foodCalculation.food.name}}</td>
          <td>{{foodCalculation.gram_amount}} g</td>
          <td>{{foodCalculation.kcal}} kcal</td>
          <td>{{foodCalculation.proteina}} g</td>
          <td>{{foodCalculation.cho}} g</td>
          <td>{{foodCalculation.lipideos}} g</td>
          <td class="text-center">
            <button class="btn btn--principal btn--xs" ng-click="edtiFoodCalc(selectedmealcalc, foodCalculation, $index)">Editar</button>
            <button class="btn btn--principal btn--xs" ng-click="removeFoodCalc(selectedmealcalc, foodCalculation)">Remover</button>
          </td>
        </tr>

然后我创建一个如上所述的指令。

<div class="row">
  <div class="col-md-12" ng-show="( items | filter: { food_option: option } ).length > 0">
    Opção {{ option }}
    <table class="table table-calculo table-striped">
      <thead>
        <tr>
          <th>Alimento</th>
        </tr>
      </thead>
      <tbody>
        <tr ng-repeat="foodCalculation in ( items | filter: { food_option: option } ) track by $index">
          <td>{{foodCalculation.food.name}}</td>
          <td class="text-center">
            <button class="btn btn--principal btn--xs" ng-click="edtiFoodCalc(selectedmealcalc, foodCalculation, $index)">Editar</button>
            <button class="btn btn--principal btn--xs" ng-click="removeFoodCalc(selectedmealcalc, foodCalculation)">Remover</button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</div>

我在'calculate-td-plan.html'中称之为

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

这是我的指令JS。

'use strict';

angular.module('nutriApp').directive('mealOption', ['$compile', function($compile) {
  var mealOption = {
    restrict: 'E',
    templateUrl: 'views/checkins/meal-options.html',
    require: 'foodSelector',
    scope: {
      option: "@",
      items: "=",
      selectedmealcalc: "="
    }
  };

  mealOption.controller = ['$scope', 'Food', function($scope, Food) {
    $scope.sumFood = {};
    $scope.summerizeOption = function(foods) {
      if(foods.length > 0){
          $scope.sumFood = Food.summerize(foods);
      }
    };
  }];

  return mealOption;

}]);

但是现在我打电话给edtiFoodCalcremoveFoodCalc的功能都不起作用。

当我将ng-controller放在我的指令中时,它可以工作,(只调用方法)但是我无法获得相同的范围。

<div class="row" ng-controller="CheckinsPlansCtrl">

我正在尝试使用edtiFoodCalc进行编辑,但我没有得到我想要的结果。我认为ng-controller在我ng-repeat时会创建新的范围,而当我没有指令时,代码会有效。

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

1 个答案:

答案 0 :(得分:1)

您可以使用angular的&绑定,它允许指令的范围将值传递回父范围。这些值不需要在控制器中定义 - 它们可以在指令中定义,然后发送回控制器。

例如,给定一个控制器和指令:

// Controller
app.controller('MainCtrl', function($scope) {  
  $scope.funcA = function(value, index) {
    console.log("Called funcA from " + value + " with index " + String(index));
  };

  $scope.funcB = function(value, index) {
    console.log("Called funcB from " + value + " with index " + String(index));
  }
});

// Directive
app.directive('arrayDirective', function() {
  return {
    templateUrl: "array_directive.html",
    scope: {
      controllerFuncA: "&controllerFuncA",
      controllerFuncB: "&controllerFuncB"
    },
    link: function (scope, element, attr) {
      scope.items = ["a","b","c","d","e"];

      scope.callControllerFuncA = function(i) {
        console.log("Calling controller funcA!");
        scope.controllerFuncA({from: "directive", index: i});
      };

      scope.callControllerFuncB = function(i) {
        console.log("Calling controller funcB!");
        scope.controllerFuncB({from: "directive", index: i});
      };   
    }
  };
});

以下模板:

<!-- Controller template -->
<body ng-controller="MainCtrl">
  <array-directive controller-func-a="funcA(from, index)" controller-func-b="funcB(from, index)"></array-directive>
</body>

<!-- Directive template -->
<div>
  <div ng-repeat="item in items">
    <div>{{item}}</div> 
    <div><a href="#" ng-click="callControllerFuncA($index)">Call Controller Func A</a></div>
    <div><a href="#" ng-click="callControllerFuncB($index)">Call Controller Func B</a></div>
  </div>
</div>

然后,您可以在指令中使用controllerFuncAcontrollerFuncB来调用相应的父控制器函数funcAfuncB。请注意,这些指令函数将对象作为参数,其中对象的键对应于您传递到<array-directive>标记上的指令的键。

请参阅随附的小提琴并观看开发者控制台以获取完整示例:https://plnkr.co/edit/3h8J00ndBk4OQ16C8hf2