search

Home  >  Q&A  >  body text

javascript - 如何在外部访问angular中directive里面的函数?

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

app.directive('bdmap', [ function(){
    return {
        restrict: 'E',
        template: '<p id="position_jsop">the detail of map</p><p id="allmap">mapview</p>',
        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(){

        },

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

怪我咯怪我咯2899 days ago291

reply all(3)I'll reply

  • 黄舟

    黄舟2017-04-10 15:15:20

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

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

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

    javascriptwindow.__map[key] = window.__map[key] || function () {};
    

    reply
    0
  • PHP中文网

    PHP中文网2017-04-10 15:15:20

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

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-10 15:15:20

    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});

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

    reply
    0
  • Cancelreply