以下直接代码来自http://jsfiddle.net/M6RPn/26/ 我想获取具有很多纬度和经度的json提要。我可以在Angular中轻松获得带有$ resource或$ http的json,但是如何获得将其输入此指令以在地图上映射事物?
module.directive('sap', function() { return { restrict: 'E', replace: true, template: '<div></div>', link: function(scope, element, attrs) { var map = L.map(attrs.id, { center: [40, -86], zoom: 10 }); //create a CloudMade tile layer and add it to the map L.tileLayer('http://{s}.tile.cloudmade.com/57cbb6ca8cac418dbb1a402586df4528/997/256/{z}/{x}/{y}.png', { maxZoom: 18 }).addTo(map); //add markers dynamically var points = [{lat: 40, lng: -86},{lat: 40.1, lng: -86.2}]; for (var p in points) { L.marker([points[p].lat, points[p].lng]).addTo(map); } } }; });
我对Leaflet或您要做什么不了解很多,但是我假设您想将一些坐标从控制器传递到指令中?
实际上,有很多方法可以做到这一点……最好的方法就是利用范围。
这是将数据从控制器传递到指令的一种方法:
module.directive('sap', function() { return { restrict: 'E', replace: true, template: '<div></div>', link: function(scope, element, attrs) { var map = L.map(attrs.id, { center: [40, -86], zoom: 10 }); //create a CloudMade tile layer and add it to the map L.tileLayer('http://{s}.tile.cloudmade.com/57cbb6ca8cac418dbb1a402586df4528/997/256/{z}/{x}/{y}.png', { maxZoom: 18 }).addTo(map); //add markers dynamically var points = [{lat: 40, lng: -86},{lat: 40.1, lng: -86.2}]; updatePoints(points); function updatePoints(pts) { for (var p in pts) { L.marker([pts[p].lat, pts[p].lng]).addTo(map); } } //add a watch on the scope to update your points. // whatever scope property that is passed into // the poinsource="" attribute will now update the points scope.$watch(attr.pointsource, function(value) { updatePoints(value); }); } }; });
这是标记。在这里,您要添加该pointsource属性,链接功能正在寻找设置$ watch的方法。
<div ng-app="leafletMap"> <div ng-controller="MapCtrl"> <sap id="map" pointsource="pointsFromController"></sap> </div> </div>
然后,在您的控制器中就有一个属性,可以更新。
function MapCtrl($scope, $http) { //here's the property you can just update. $scope.pointsFromController = [{lat: 40, lng: -86},{lat: 40.1, lng: -86.2}]; //here's some contrived controller method to demo updating the property. $scope.getPointsFromSomewhere = function() { $http.get('/Get/Points/From/Somewhere').success(function(somepoints) { $scope.pointsFromController = somepoints; }); } }