如何将参数传递给控制器​​中定义但从 Angularjs 中的指令调用的方法? [英] How to pass argument to method defined in controller but called from directive in Angularjs?

查看:12
本文介绍了如何将参数传递给控制器​​中定义但从 Angularjs 中的指令调用的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将一个参数从指令传递给控制器​​中定义的方法.

我使用隔离范围.

这是相关代码和Fiddle中的演示:

HTML

 

<map id="map_canvas" call='callMe()'></map>

JS

var module = angular.module('googleMap', []);module.directive('map', function() {返回 {限制:'E',替换:真的,范围:{callMe : '&call'},模板:'<div></div>',链接:函数(范围,元素,属性){控制台日志(元素);/* ... */scope.callMe('嘿');/* ... */}};});函数 MapCtrl($scope) {$scope.callMe = 函数(val){警报(val);};}

为什么我得到 val=undefined?应该是

谢谢,

解决方案

你需要注释你的函数参数:

小提琴

查看:

<map id="map_canvas" call='callMe(param)'></map>

指令:

scope.callMe({param: 'hey'});

这是在文档中解释(虽然有点含糊):

<块引用>

&或 &attr - 提供一种在上下文中执行表达式的方法父作用域.如果未指定属性名称,则属性名称假定与本地名称相同.范围的给定和小部件定义:{localFn:'&myAttr' },然后隔离范围属性 localFn 将指向count = count + value 表达式的函数包装器.经常通过表达式从隔离范围传递数据是可取的和父作用域,这可以通过传递本地映射来完成变量名和值放入表达式包装器 fn 中.例如,如果表达式是 increment(amount) 那么我们可以指定数量值通过调用 localFn 作为 localFn({amount: 22}).

I try to pass one parameter from directive to method defined in controller.

I use isolate scope.

Here is relevant code and Demo in Fiddle:

HTML

 <div ng-controller="MapCtrl">
        <map id="map_canvas" call='callMe()'></map>
    </div>

JS

var module = angular.module('googleMap', []);

module.directive('map', function() {
    return {
        restrict: 'E',
        replace: true,
        scope:{
            callMe : '&call'
        },
        template: '<div></div>',
        link: function(scope, element, attrs) {
            console.log(element);

           /* ... */                
           scope.callMe('hey');

           /* ... */                                
        }
    };
});

function MapCtrl($scope) {

    $scope.callMe = function(val){
    alert(val);
    };

}

Why I get val=undefined? It should be hey

Thanks,

解决方案

You need to annotate your function parameters:

FIDDLE

View:

<map id="map_canvas" call='callMe(param)'></map>

Directive:

scope.callMe({param: 'hey'});

This is explained in the docs (although somewhat vaguely):

& or &attr - provides a way to execute an expression in the context of the parent scope. If no attr name is specified then the attribute name is assumed to be the same as the local name. Given and widget definition of scope: { localFn:'&myAttr' }, then isolate scope property localFn will point to a function wrapper for the count = count + value expression. Often it's desirable to pass data from the isolated scope via an expression and to the parent scope, this can be done by passing a map of local variable names and values into the expression wrapper fn. For example, if the expression is increment(amount) then we can specify the amount value by calling the localFn as localFn({amount: 22}).

这篇关于如何将参数传递给控制器​​中定义但从 Angularjs 中的指令调用的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆