在不同的attr中定义的指令attr内的回调函数

编程入门 行业动态 更新时间:2024-10-12 05:50:00
本文介绍了在不同的attr中定义的指令attr内的回调函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

所以我有这个指令叫做说,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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-21 22:20:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1010800.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:回调   指令   函数   定义   attr

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!