把$scope函数传递给指令

Angular - pass $scope function to directive

本文关键字:指令 函数 scope      更新时间:2023-09-26

我通过html属性将控制器$scope函数传递给指令,但由于某种原因,指令认为该函数是字符串。有提示吗?

HTML

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

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.createNewCustomer = function(){
    alert('yo')
  }

最好的,奥斯汀

你的代码应该是:

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

很可能立即调用函数并传入结果

在您的指令中,您已经通过在隔离作用域中使用&参数将scope.createNewCustomer绑定到函数。但是,当您通过attrs重新分配它时,您实际上用字符串值覆盖该函数。attrs只是一个键值对数组,它们是元素中每个属性的字符串表示形式。

AngularJs指令允许你通过两种方式在作用域中使用'&'方法。第一种方法允许你在独立指令中传递参数。第二个让你在指令外传递参数,但调用INSIDE ISOLATED指令。像

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

如果你想了解更多,这里有一篇很酷的文章和例子:

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