私はAngularJSの初心者で、MapControllerのgetMyPosition()関数でuserLocationディレクティブのgoToUserLocation()関数を使用しようとしています。私がこれをやりたいのは、ユーザーがボタンをクリックすると、自分の位置を取得し、40にズームインしてマップの中央に配置したいからです。 誰か助けてもらえますか? ありがとうございます。ここ はディレクティブ、コントローラおよびディレクティブが使用するサービスです。ここコントローラー関数内でディレクティブの関数を使用するにはどうすればよいですか?
(function()
{
'use strict';
angular
.module('app.map')
.directive('userLocation', userLocation);
function userLocation(geolocation)
{
return {
restrict: "A",
link: function(scope, element, attrs){
var ctrl = scope['vm'];
var goToUserLocation = UserLocationFactory();
goToUserLocation(ctrl, geolocation, ctrl.defaultLocation);
}
};
}
//Factory to build goToUserLocation function with callbacks configuration
function UserLocationFactory(cantGetLocation, notSupportedBrowser)
{
return goToUserLocation;
//function to make the map go to user location
function goToUserLocation(vm, geolocation, defaultLocation)
{
resolveErrorCallbacks();
geolocation.goToUserLocation(success, cantGetLocation, notSupportedBrowser);
function success(position)
{
var location = {
lat: position.lat,
lng: position.lng,
zoom: 15
};
configureLatlng(location);
}
function configureLatlng(location)
{
vm.map = {
center: location
};
}
function resolveErrorCallbacks(){
if(!cantGetLocation || !(typeof cantGetLocation === "function"))
{
cantGetLocation = function()
{
configureLatlng(defaultLocation);
};
}
if(!notSupportedBrowser || !(typeof notSupportedBrowser === "function"))
{
notSupportedBrowser = function()
{
configureLatlng(defaultLocation);
};
}
}
}
}
})();
はコントローラである:ここでは
(function()
{
'use strict';
angular
.module('app.map')
.controller('MapController', MapController);
/** @ngInject */
function MapController($mdDialog, $mdSidenav, $animate, $timeout, $scope, $document, MapData,
leafletData, leafletMapEvents, api, prototypes, $window, appEnvService, geolocation) {
var vm = this;
vm.getMyPosition = getMyPosition;
function getMyPosition(){
console.log("Here is your location.");
}
は、ディレクティブは、私たちのサービスです。
(function() {
'use strict';
angular
.module('app.map')
.service('geolocation', geolocation);
function geolocation() {
/*
success - called when user location is successfully found
cantGetLocation - called when the geolocation browser api find an error in retrieving user location
notSupportedBrowser - callend when browser dont have support
*/
this.goToUserLocation = function(success, cantGetLocation, notSupportedBrowser)
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(currentPosition, function() {
cantGetLocation();
});
}
else
{
// Browser doesn't support Geolocation
notSupportedBrowser();
}
function currentPosition(position)
{
var pos =
{
lat: position.coords.latitude,
lng: position.coords.longitude
};
success(pos);
}
};
}
})();
これは命令のコントローラーではありませんか?もしそうでなければ、そうするのが得策でしょうか?次に、$ scope.method()を使用して、 – rrd