在不同的attr中定义的指令attr内的回调函数 [英] Callback function inside directive attr defined in different attr

查看:24
本文介绍了在不同的attr中定义的指令attr内的回调函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这个指令叫做说,mySave,它几乎就是这个

So I have this directive called say, mySave, it's pretty much just this

app.directive('mySave', function($http) {
   return function(scope, element, attrs) {
      element.bind("click", function() {
          $http.post('/save', scope.data).success(returnedData) {
              // callback defined on my utils service here

              // user defined callback here, from my-save-callback perhaps?
          }
      });
   }
});

元素本身看起来像这样

<button my-save my-save-callback="callbackFunctionInController()">save</button>

callbackFunctionInController 现在只是

callbackFunctionInController is for now just

$scope.callbackFunctionInController = function() {
    alert("callback");
}

当我 console.log() attrs.mySaveCallback 在 my-save 指令中时,它只给我一个字符串 callbackFunctionInController(),我读到某处,我应该 $parse 这个,它会没事,所以我尝试 $parse(attrs.mySaveCallback) 这给了我一些功能,但几乎不是我正在寻找的,它给了我

when I console.log() attrs.mySaveCallback inside my-save directive, it just gives me a string callbackFunctionInController(), I read somewhere that I should $parse this and it would be fine, so I tried to $parse(attrs.mySaveCallback) which gave me back some function, but hardly the one I was looking for, it gave me back

function (a,b){return m(a,b)} 

我做错了什么?这种方法从一开始就有缺陷吗?

What am I doing wrong? Is this approach flawed from the beginning?

推荐答案

所以看起来最好的方法是使用 ProLoser 建议的隔离作用域

So what seems like the best way is using the isolated scope as suggested by ProLoser

app.directive('mySave', function($http) {
   return {
      scope: {
        callback: '&mySaveCallback'
      }
      link: function(scope, element, attrs) {
        element.on("click", function() {
            $http.post('/save', scope.$parent.data).success(returnedData) {
                // callback defined on my utils service here

                scope.callback(); // fires alert
            }
        });
      }
   }
});

要将参数传回控制器,请执行此操作

For passing parameters back to controller do this

[11:28] <revolunet> you have to send named parameters 
[11:28] <revolunet> eg my-attr="callback(a, b)" 
[11:29] <revolunet> in the directive: scope.callback({a:xxx, b:yyy})

这篇关于在不同的attr中定义的指令attr内的回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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