javascript 将参数从指令传递给控制器函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19150213/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pass Arguments from directive to controller function
提问by C-Rad
I've seen lots of these questions but haven't found a solution that works. here is a fiddle that doesn't work but should.
我见过很多这样的问题,但还没有找到有效的解决方案。这是一个不起作用但应该的小提琴。
http://jsfiddle.net/cdparmeter/j2K7N/2/
http://jsfiddle.net/cdparmeter/j2K7N/2/
Controller:
控制器:
$scope.foo = function (textArray) {
console.log(textArray)
};
Directive:
指示:
return {
restrict: 'E',
replace: 'true',
scope: {
methodToCall: '&method'
},
template: "<div>
<input ng-model='textToPush'/>
<button ng-click='pushText'>Push</button>
<button ng-click='finish'>Finish</button>
</div>",
link: function (scope, element, attrs) {
scope.paragraphs = [];
scope.pushText = function () {
scope.paragraphs.push(scope.pushText);
scope.pushText = "";
}
scope.finish = function () {
scope.methodToCall(scope.paragraphs)
}
}
}
HTML:
HTML:
<div ng-app="MyApp">
<div ng-controller="MyController">
<container data-method="foo">
</div>
</div>
I'm building an array inside my directive that needs custom handling in the controller of the parent scope. I know I can throw a watch in the parent scope on a model I pass into my directive but that seems hackish and dirty. any suggestions?
我正在我的指令中构建一个数组,该数组需要在父作用域的控制器中进行自定义处理。我知道我可以在传递给我的指令的模型的父作用域中扔一块手表,但这看起来很黑很脏。有什么建议?
回答by Michael Benford
Before answering your question I must say that your script contains a few errors:
在回答您的问题之前,我必须说您的脚本包含一些错误:
- You're binding the input to a variable called
textToPush
, and then using a different one inside thepushText
function (pushText
); - You're not setting the
ng-click
directive correctly; it should beng-click="pushText()"
instead ofng-click="pushText"
. The same forfinish
;
- 您将输入绑定到一个名为 的变量
textToPush
,然后在pushText
函数 (pushText
) 中使用不同的变量; - 您没有
ng-click
正确设置指令;它应该ng-click="pushText()"
代替ng-click="pushText"
. 相同的finish
;
Now, back to your question. In order to call a function of the parent scope passing arguments, you can get a reference to that function first, and then execute it:
现在,回到你的问题。为了调用父作用域传递参数的函数,您可以先获取对该函数的引用,然后执行它:
scope.finish = function () {
var func = scope.methodToCall();
func(scope.paragraphs);
}
Here's a working versionof your script.
这是您的脚本的工作版本。
You could also do this, if you prefer:
如果您愿意,也可以这样做:
scope.finish = function () {
scope.methodToCall({value: scope.paragraphs});
}
But for this code to work you should change your markup to:
但是要使此代码正常工作,您应该将标记更改为:
<container data-method="foo(value)"/>
Here's another jsFiddleshowing the solution above.