Angular Way:
What we want to be able to do is separate the scope inside a directive from the scope outside, and then map the outer scope to a directive's inner scope.
See this example:
angular.module('Ski').directive('mapCanvas', function() {
return {
scope: {
lat: '=',
lng: '='
},
link: function(scope, element, attrs) {
var zoom = attrs.zoom || 14;
var myLatlng = new google.maps.LatLng(scope.lat, scope.lng);
var mapOptions = {
center: myLatlng,
zoom: zoom
};
var map = new google.maps.Map(element[0], mapOptions);
}
};
});
And setup it like this:
<div map-canvas lat="lat" lng="lng" zoom="14">
<!-- your content, zoom is optional-->
</div>
Where lat and lng are binded to the controller $scope.lat and $scope.lng
Runnable Example with Map
Empiric
angular.module('ski',[])
.controller('ctrl', function($scope) {
$scope.lat = 40.71427;
$scope.lng = -74.00597;
$scope.extra = "New York City";
})
.directive('map', function() {
return {
restrict: 'E',
scope: {
lat: '=',
lng: '='
},
replace: true,
template:'<div class="fullscreen"></div>',
link: function(scope, element, attrs) {
var zoom = parseInt(attrs.zoom) || 14;
var myLatlng = new google.maps.LatLng(scope.lat, scope.lng);
var mapOptions = {
center: myLatlng,
zoom: zoom
};
var map = new google.maps.Map(element[0], mapOptions);
}
};
});
html, body, .fullscreen {
width: 100%;
height: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?key=&sensor=false&extension=.js"></script>
<div ng-app="ski" ng-controller="ctrl" class="fullscreen">
<map lat="lat" lng="lng" zoom="12" ></map>
</div>
Runnable Example without Map
Conceptual.
angular.module('ski',[])
.controller('ctrl', function($scope) {
$scope.lat = -32.634;
$scope.lng = -54.534;
$scope.extra = "Angular Way";
})
.directive('mapCanvas', function() {
return {
// creates new isolated scope.
scope: {
lat: '=',
lng: '='
},
// here lat, lng, other & extra refers to directive isolated scope, not controller scope.
template: '<p> Lat: {{lat}} Lng: {{lng}} Other: {{other}} Extra: {{extra}}</p>',
link: function(scope, element, attrs) {
// here scope means directive isolated scope.
var zoom = attrs.zoom || 14;
var extra = attrs.extra || "no extra";
scope.other = zoom ;
scope.extra = extra;
console.log(scope.lat, scope.lng);
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="ski" ng-controller="ctrl">
<div map-canvas lat="lat" lng="lng" zoom="14" extra="{{extra}}">
<!-- your content, zoom is optional-->
</div>
</div>