在外部控制器指令内调用控制器的功能

时间:2016-05-10 07:25:25

标签: javascript angularjs cordova ionic-framework

我正在创建一个离子应用程序,可以在地图上使用研究和路线。您输入所需的位置,它已经为您提供了从当前位置到所需位置的路线。它工作得很好。唯一的问题是我需要调用一个位于地图控制器内的函数,我需要这个函数在控制器外部的指令工作之后运行。 简单来说,我需要在指令中调用控制器的函数。 我在互联网上看到了一些例子,但在这些例子中我没有成功,我希望你能帮助我。

示例:

.controller("atigmaps", function($ scope, $ state, $ ionicModal, $ rootScope) {
    $ Scope.load_map = function() {
        /// ...    
    }
})

.directive('example', function($ ionicModal, LocationService) {
             $ Scope.choosePlace = function(place) {
                 LocationService.getDetails(place.place_id).then(function(location) {
                     $ Scope.location = location;
                     $ Scope.close();
                     $ Scope.load_map() < -- - This

                 function is within the controller
             });
         };
     }

我的功能

var geocoder;
var map;
var marker;



geocoder = new google.maps.Geocoder();

    marker = new google.maps.Marker({
        map: $scope.model.myMap,
        draggable: true,
        icon:'pin_route.png',
    });





function carregarNoMapa(endereco) {

        geocoder.geocode({ 'address': endereco + ', Brasil', 'region': 'BR' }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[0]) {
                    var latitude = results[0].geometry.location.lat();
                    var longitude = results[0].geometry.location.lng();

                    $('#txtEndereco').val(results[0].formatted_address);
                    $('#txtLatitude').val(latitude);
                    $('#txtLongitude').val(longitude);
                    $('#dest').val(document.getElementById('txtEndereco').value);





                    $scope.atualizalocation();

                    var location = new google.maps.LatLng(latitude, longitude);
                    marker.setPosition(location);
                    $scope.calcRoute();
                    $scope.model.myMap.setCenter(location);
                    $scope.model.myMap.setZoom(15);

                }
            }
        });
    }

我的指示

.directive('locationSuggestion', function($ionicModal, LocationService){
  return {
    restrict: 'A',
    scope: {
      location: '='
    },
    link: function($scope, element){
      console.log('locationSuggestion started!');
      $scope.search = {};
      $scope.search.suggestions = [];
      $scope.search.query = "";
      $ionicModal.fromTemplateUrl('location.html', {
        scope: $scope,
        focusFirstInput: true
      }).then(function(modal) {
        $scope.modal = modal;
      });
      element[0].addEventListener('focus', function(event) {
        $scope.open();
      });
      $scope.$watch('search.query', function(newValue) {
        if (newValue) {
          LocationService.searchAddress(newValue).then(function(result) {
            $scope.search.error = null;
            $scope.search.suggestions = result;
          }, function(status){
            $scope.search.error = "There was an error :( " + status;
          });
        };
        $scope.open = function() {
          $scope.modal.show();
        };
        $scope.close = function() {
          $scope.modal.hide();
        };






        $scope.choosePlace = function(place) {
          LocationService.getDetails(place.place_id).then(function(location) {
            $scope.location = location;
            $scope.close();








          });
        };
      });
    }
  }




})

2 个答案:

答案 0 :(得分:1)

您应该在工厂中包含您的功能,在控制器和指令中包含工厂,并调用如下函数:MyFactory.load_map()

样品:

factory.js

angular.module('starter.factoryServices', [])

  .factory('MyFactory', function($q) {

    return {
          load_map : function() {
               /// ...    
           }
      }


  });

您的代码:

.controller("atigmaps", function($ scope, $ state, $ ionicModal, $ rootScope, MyFactory) {

})

.directive('example', function($ ionicModal, LocationService, MyFactory) {
             $ Scope.choosePlace = function(place) {
                 LocationService.getDetails(place.place_id).then(function(location) {
                     $ Scope.location = location;
                     $ Scope.close();
                     MyFactory.load_map(); 

             });
         };
     }

在角度模块中:

angular.module('starter', ['ionic', 'starter.factoryServices'])

并在index.html中添加引用

<script src="path/myFactory.js"></script>

答案 1 :(得分:1)

假设你谈到的指令是你的,你可以使用&#39;&amp;&#39;用于公开控制器api的符号(请参阅here以获取文档,它表示&#34;组件&#34;但它也适用于指令)。以下是我使用的指令示例:

(function() {
  'use strict';

  angular
    .module('app')
    .directive('tabs', tabs);

  /** @ngInject */
  function tabs() {
    var directive = {
      templateUrl: 'app/components/tabs/tabs.component.html',
      controller: 'TabsController',
      controllerAs: 'vm',
      bindToController: {
        id: '@',
        onApiReady: '&'
      },
      scope:{}
    };

    return directive;
  }
})();

这是相关的控制器:

(function() {
  'use strict';

  angular
    .module('app')
    .controller('TabsController', TabsController);

  /** @ngInject */
  function TabsController(TabList) {
    var vm = this, api;
    vm.$onInit = activate;

    api = {
      addTab: addTab
    };

    ////////////////////////////////////////////

    function activate() {
      vm.tabList = new TabList(vm.id);

      if(vm.onApiReady){
        vm.onApiReady({api: api});
      }
    }

    function addTab(tab) {
      vm.tabList.addTab(tab);
    }
  }
})();

这是调用我创建的指令的HTML

<div ng-controller="MainController as vm">
    <tabs id="main-tabs" on-api-ready="vm.onTabsApiReady(api)"></tabs>
</div>

最后是MainController

(function() {
  'use strict';

  angular
    .module('app')
    .controller('MainController', MainController);

  /** @ngInject */
  function MainController(mainService) {
    var vm;
    vm = this;
    vm.$onInit = activate;
    vm.onTabsApiReady = onTabsApiReady;

    ///////////////////////////////////////

    function activate() {}

    function onTabsApiReady(tabList){
      var i, tabs = ['tab1','tab2'];

      for(i = 0 ; i < tabs.length ; ++i){
        tabList.addTab(tabs[i]);
      }
    }

  }
})();