在控制器指令内传递数据的NG-点击进入一个函数 [英] Passing data from ng-click within directive into a function in the controller
问题描述
我发现这个问题,这让我几乎到了我需要的人。
<一href=\"http://stackoverflow.com/questions/17567383/why-doesnt-ng-click-work-in-my-directive-and-how-do-i-add-a-toggle-class\">Why在我的指令不NG-单击工作,我怎么添加切换类?
I found this question which gets me almost to where I need to be. Why doesn't ng-click work in my directive and how do I add a toggle class?
这使得它,所以我的我的指令模板中的NG-点击触发我的控制器的功能。
http://plnkr.co/edit/GorcZZppa8qcIKbQAg2v?p=$p$pview一>
Which makes it so my ng-click within my directive template triggers a function in my controller. http://plnkr.co/edit/GorcZZppa8qcIKbQAg2v?p=preview
问题是,参数恢复到我的控制器(项目)未定义。我需要这实际上是我的指令中传递从变量数据,我会在控制器运行函数中使用。
The issue is that the parameter returned to my controller (item) is undefined. I need this to actually pass data from a variable within my directive to be used in the function that I will run in the controller.
指令模板文件
<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());
}
的(项目)未定义的
推荐答案
虽然传递函数指令隔离的范围,你应该使用&安培;
(例如pression结合)来传递方法参考。在项单击
你应该提到的像 toggleInBasket到控制器的方法实际调用(项目)
While passing function to directive isolated scope, you should be using &
(expression binding) to pass method reference. On item-click
you should mentioned actual call to controller method like toggleInBasket(item)
标记
<listitem item="item" item-click="toggleInBasket(item)"></listitem>
然后一边从指令调用的方法,你应该称呼其为 scope.itemClick({项目:项目})
指令
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
}
}
}
});
这篇关于在控制器指令内传递数据的NG-点击进入一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!