将指令内的ng-click中的数据传递到控制器中的函数中



我发现了这个问题,它几乎让我达到了我需要的地方。为什么不';在我的指令中点击工作,以及如何添加切换类?

这使得我在指令模板中的ng点击触发了控制器中的一个函数。http://plnkr.co/edit/GorcZZppa8qcIKbQAg2v?p=preview

问题是返回到我的控制器(项)的参数未定义。我需要它来实际传递指令中变量的数据,以便在控制器中运行的函数中使用。

指令模板文件

<div class="tsProductAttribute" 
        ng-class="{'tsProductAttribute--selected': selected}" 
        ng-click="toggleState(item)">
    <span class="tsProductAttribute-image">
        <img ng-src="{{variantImage}}">
    </span>
    <span class="tsProductAttribute-desc">{{item.productName}}</span>
    <select ng-model="variantImage">
        <option  ng-repeat="variant in item.variants" value="{{variant.image}}">{{variant.name}} - {{variant.listprice.amount}}</option>
    </select>
    <span class="tsProductAttribute-price">{{item.variants[0].listprice.amount}} {{item.variants[0].listprice.entity}}</span>
</div>

指令

angular.module('msfApp')
.directive('listitem', function () {
    return {
        templateUrl: 'assets/templates/directives/listitem.html',
        restrict: 'E',
        scope: {
            'item': '=',
            'itemClick': '&'
        },
        link: function(scope, iElement, iAttrs) {
          scope.selected = false;
          scope.toggleState = function(item) {
            scope.selected = !scope.selected;
            scope.itemClick(item);
          }
        }
    }
});

指令执行

<listitem item="item" item-click="toggleInBasket(item)"></listitem>

控制器中的功能

$scope.toggleInBasket = function(item) {
        $scope.basket.toggle(item);
        console.log(basket.get());
    }

(项)未定义

在将函数传递到指令隔离的作用域时,应该使用&(表达式绑定)来传递方法引用。在item-click上,您应该提到对控制器方法的实际调用,如toggleInBasket(item)

标记

<listitem item="item" item-click="toggleInBasket(item)"></listitem>

然后在从指令调用方法时,应该将其称为scope.itemClick({item: item})

指令

angular.module('msfApp').directive('listitem', function () {
  return {
    templateUrl: 'listitem.html',
    restrict: 'E',
    scope: {
      'item': '=',
      'itemClick': '&' // & changed to expression binding
    },
    link: function(scope, iElement, iAttrs) {
      scope.selected = false;
      scope.toggleState = function(item) {
        scope.selected = !scope.selected;
        scope.itemClick({item: item}); //changed call to pass item value
      }
    }
  }
});

此处演示

最新更新