javascript - 如何在外部访问angular中directive里面的函数?
怪我咯
怪我咯 2017-04-10 15:13:20
[JavaScript讨论组]

如题,我在directive里面定义了百度地图的异步加载,可是在加载完成后浏览器提示没有找到那个回调,请问如何定义可以让回调执行起来?

app.directive('bdmap', [ function(){
    return {
        restrict: 'E',
        template: '

the detail of map

mapview

', transclude: true, link: function($scope, iElm, iAttrs, controller) { var map = { options:{ enableHighAccuracy:true, maximunAge:3000, timeout:45000, }, loadMapScript:function(){ var self = this var script = document.createElement("script"); script.type = "text/javascript"; script.src = "http://api.map.baidu.com/api?v=2.0&ak=xcjT5073PywMq4XHWxXG8yfF&callback=map.initMap"; //就是这里,它会执行一次map.initMap之前map在window下是可以运行initmap的,放在directive里面就不可以了 document.getElementById(self.instanceData.scriptPutId).appendChild(script); var script_coverter = document.createElement("script"); script_coverter.type = "text/javascript"; script_coverter.src = "http://developer.baidu.com/map/jsdemo/demo/convertor.js" document.getElementById(self.instanceData.scriptPutId).appendChild(script_coverter); }, initMap:function(){ },

请问遇到这种问题该如何解决?

怪我咯
怪我咯

走同样的路,发现不同的人生

全部回复(3)
黄舟

百度地图url上得callback=map.initMap查找的window作用于下的对应方法。而楼主代码中定义的回调方法是存放在 directive 自己的私有作用于内,百度当然找不到。所以最后还是应该把回调函数定义在window下。

javascriptwindow.__map.initMap = window.__map.initMap || function () {};

如果需要有多个回调,可以尝试用对象存储一个地图回调集合, directive中通过 key 来制定对应的回调函数。

javascriptwindow.__map[key] = window.__map[key] || function () {};
PHP中文网

你可以理解为百度地图那种是通过jsonp的形式初始化的,而那个map必须是全局window下的

天蓬老师

directive中的scope三种形式:
@ 字符串传递
= 双向绑定
& 表达式和函数

可使用&实现directive来调用回调函数,如下伪代码:
directive:
name: temp
scope: {
callback: &
}

<temp callback='testFunc' />

若回调函数存在参数,你需要在directive调用callback时指定参数,如下伪代码:
假设testFunc = function(arg1, args) {...}

<temp callback='testFunc(arg1, args2)' />

在directive中使用方式:
$scope.callback({arg1: 1, arg2: 2});

具体你可以实践下就知道了

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号