C-R*_*Rad 8 javascript angularjs angularjs-directive angularjs-controller
我已经看到很多这些问题,但没有找到有效的解决方案.这是一个小提琴,不起作用但应该.
http://jsfiddle.net/cdparmeter/j2K7N/2/
控制器:
$scope.foo = function (textArray) {
console.log(textArray)
};
Run Code Online (Sandbox Code Playgroud)
指示:
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)
}
}
}
Run Code Online (Sandbox Code Playgroud)
HTML:
<div ng-app="MyApp">
<div ng-controller="MyController">
<container data-method="foo">
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
我正在我的指令中构建一个数组,需要在父作用域的控制器中进行自定义处理.我知道我可以在我传递给我的指令的模型上的父范围内抛出一块手表,但这看起来很黑而且很脏.有什么建议?
Mic*_*ord 13
在回答您的问题之前,我必须说您的脚本包含一些错误:
textToPush
,然后在pushText
函数(pushText
)中使用另一个变量;ng-click
正确设置指令; 它应该是ng-click="pushText()"
而不是ng-click="pushText"
.同样的finish
;现在,回到你的问题.为了调用父作用域传递参数的函数,您可以首先获得对该函数的引用,然后执行它:
scope.finish = function () {
var func = scope.methodToCall();
func(scope.paragraphs);
}
Run Code Online (Sandbox Code Playgroud)
这是您脚本的工作版本.
如果您愿意,也可以这样做:
scope.finish = function () {
scope.methodToCall({value: scope.paragraphs});
}
Run Code Online (Sandbox Code Playgroud)
但是要使此代码工作,您应该将标记更改为:
<container data-method="foo(value)"/>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9975 次 |
最近记录: |