【问题标题】:Passing data from ng-click within directive into a function in the controller将数据从 ng-click inside 指令传递到控制器中的函数
【发布时间】:2016-03-24 20:42:04
【问题描述】:

我发现这个问题让我几乎到达了我需要的地方。 Why doesn't ng-click work in my directive and how do I add a toggle class?

这使得我在指令模板中的 ng-click 触发了我的控制器中的一个函数。 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());

    }

(项目)未定义

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-scope isolate-scope


    【解决方案1】:

    在将函数传递给指令隔离作用域时,您应该使用&amp;(表达式绑定) 来传递方法引用。在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
          }
        }
      }
    });
    

    Demo here

    【讨论】:

    • 谢谢,这似乎奏效了。让我在我的实时代码上试试看:)
    • @mcestone 很高兴听到这个消息。谢谢:-)
    • 成功了!!谢谢你的帮助,我真的很感激。
    • @mcestone 没问题。干杯和感谢:-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多