将Arguments从指令传递给控制器​​函数

时间:2013-10-03 03:24:48

标签: javascript angularjs angularjs-directive angularjs-controller

我已经看到很多这些问题,但没有找到有效的解决方案。这是一个小提琴,不起作用但应该。

http://jsfiddle.net/cdparmeter/j2K7N/2/

控制器:

$scope.foo = function (textArray) {
    console.log(textArray)
};

指令:

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:

<div ng-app="MyApp">
    <div ng-controller="MyController">
        <container data-method="foo">
    </div>
</div>

我正在我的指令中构建一个数组,需要在父作用域的控制器中进行自定义处理。我知道我可以在我传递给我的指令的模型上的父范围内抛出一块手表,但这看起来很晦涩和肮脏。有什么建议吗?

1 个答案:

答案 0 :(得分:13)

在回答您的问题之前,我必须说您的脚本包含一些错误:

  1. 您将输入绑定到名为textToPush的变量,然后在pushText函数(pushText)中使用其他变量;
  2. 您没有正确设置ng-click指令;它应该是ng-click="pushText()"而不是ng-click="pushText"finish;
  3. 也是如此

    现在,回到你的问题。为了调用父作用域传递参数的函数,您可以首先获得对该函数的引用,然后执行它:

    scope.finish = function () {
      var func = scope.methodToCall();                
      func(scope.paragraphs);
    }
    

    这是您脚本的working version

    如果您愿意,也可以这样做:

    scope.finish = function () {
        scope.methodToCall({value: scope.paragraphs});                                
    }
    

    但要使此代码生效,您应该将标记更改为:

    <container data-method="foo(value)"/>
    

    这是显示上述解决方案的another jsFiddle

相关问题