directive定义当中link函数里面有些局部变量 在外层的controller当中需要使用
现在问题是这个link当中的map怎么让外面看到?
比如下面的controller当中怎么才能获取'google-map'的link函数当中定义的变量?
update:
找到方法了 scope里面加一个变量 map: "="就可以了
<div ng-controller="Demo as d">
<google-map></google-map>
</div>
(function () {
var app = angular.module('googleMap', []);
app.factory('mapsInit', function ($window, $q) {
var asyncUrl = "https://maps.googleapis.com/maps/api/js?callback=",
mapsDefer = $q.defer();
//Callback function - resolving promise after maps successfully loaded
$window.googleMapsInitialized = mapsDefer.resolve; // removed ()
//Async loader
var asyncLoad = function (asyncUrl, callbackName) {
var script = document.createElement('script');
script.src = asyncUrl + callbackName;
document.body.appendChild(script);
};
//Start loading google maps
asyncLoad(asyncUrl, 'googleMapsInitialized');
//Usage: Initializer.mapsInitialized.then(callback)
return {
mapsInitialized: mapsDefer.promise
};
})
app.directive('googleMap', function (mapsInit) {
return {
restrict: 'E',
scope: {
mapId: '@id', // map ID
lat: '@', // latitude
long: '@', // longitude
map: '=' //是一个binding attribute 会把外层model的参数update
},
link: function (scope) {
// Simple check
console.log(scope.mapId, scope.lat, scope.long);
// Check if latitude and longitude are specified
if (angular.isDefined(scope.lat) && angular.isDefined(scope.long)) {
// Initialize the map
var initialize = function () {
var location = new google.maps.LatLng(scope.lat, scope.long);
var mapOptions = {
zoom: 12,
center: location
};
//我想从外部访问这个map变量 怎么把它传递出去?
var map = new google.maps.Map(document.getElementById(scope.mapId), mapOptions);
//map.addListener('bounds_changed', mapBoundChanged);
//gMap = map;
};
// Loads google map script
mapsInit.mapsInitialized.then(function () {
// Promised resolved
initialize();
}, function () {
// Promise rejected
});
}
}
};
});
})();
--
修改:facilitator FROM 130.102.82.*
FROM 130.102.82.*