简体   繁体   English

Angular-将$ scope函数传递给指令

[英]Angular - pass $scope function to directive

I'm passing a controller $scope function to a directive through an html attribute, but for some reason the directive thinks that the function is a string. 我正在通过html属性将控制器$ scope函数传递给指令,但由于某种原因,该指令认为该函数是字符串。 Any hints? 有什么提示吗?

HTML 的HTML

<modal show='createCustomer' create-new-customer='createNewCustomer()'></modal>

Directive 指示

function modalDialog() {
  return {
    restrict: 'AE',
    scope:{
      createNewCustomer: '&'
    },
    replace: true,
    transclude: true,
    link: function(scope, element, attrs) {
      scope.createNewCustomer = attrs.createNewCustomer;
      console.log(typeof scope.createNewCustomer)
    },
    templateUrl: "./views/directive_templates/modal.html"
  };
}

$scope function $ scope函数

 $scope.createNewCustomer = function(){
    alert('yo')
  }

Best, Austin 最好的,奥斯丁

Your code should be: 您的代码应为:

<modal show='createCustomer' create-new-customer='createNewCustomer'></modal>

It is most likely invoking the function immediately and passing in the result 最有可能立即调用该函数并传递结果

In your directive, you already have scope.createNewCustomer bound to the function, through the use of the & parameter in your isolate scope. 在您的指令中,已经通过在隔离范围中使用&参数,将scope.createNewCustomer绑定到该函数。 However, you actually overwrite the function with the string value when you re-assign it through the attrs . 但是,实际上,当您通过attrs重新分配它时,会使用字符串值覆盖该函数。 attrs is simply an array of key value pairs that are the string representation of each attribute in the element. attrs只是键值对的数组,这些键值对是元素中每个属性的字符串表示形式。

AngularJs directive lets you to use '&' method in scope with 2 ways.First way lets you to pass argument inside your isolated directive.Second one lets you to pass arguments outside of directive but to call INSIDE ISOLATED DIRECTIVE.Like AngularJs指令可让您以两种方式在范围内使用'&'方法。第一种方式可让您在隔离的指令内传递参数;第二种方式可让您在指令外传递参数,但可以调用INSIDE ISOLATED DIRECTIVE。

<div my-dir func="myFunc(arg1,arg2,..)"></div>
<div my-dir func="myFunc(value1,value2,..)"></div>

If you want more here is a cool article with examples: 如果您想了解更多,这里有一篇很酷的示例文章:

http://www.w3docs.com/snippets/angularjs/angularjs-directive-scope-method.html http://www.w3docs.com/snippets/angularjs/angularjs-directive-scope-method.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM