我应该如何处理控制器之间的函数调用? [英] How should I handle function calls between controllers?

查看:21
本文介绍了我应该如何处理控制器之间的函数调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个包含全屏地图和侧边栏的 Angular 应用.

I'm trying to build an Angular app that consists of a fullscreen map and a sidebar.

我目前有一个 MapController 来设置地图,然后我有一个 PlacesController 用于在侧边栏中列出地点.如果我现在想通过单击侧边栏中的链接向地图添加标记,应如何处理?

I currently have a MapController that setups the map and then I have a PlacesController for listing places in the sidebar. If I now would like to add a marker to the map by clicking a link in the sidebar, how should this be handled?

我的想法:PlacesController 有一个名为 addMarker 的函数,该函数在使用$rootScope.$broadcast('addMarker');"广播addMarker"的服务中调用另一个名为 addMarker 的函数.MapController 侦听,然后在 MapController 中调用addMarker",实际上将标记添加到地图.

My idea: The PlacesController have a function called addMarker that calls another function called addMarker in a service that broadcasts "addMarker" using "$rootScope.$broadcast('addMarker');" which the MapController listens for and then calls "addMarker" in the MapController which actually adds the marker to the map.

有没有更简单/更好的方法来做到这一点?

Is there an easier/better way of doing this?

推荐答案

您应该将所有数据都包含在某个服务中,以便在更改时通知任何侦听器.编辑 这是一个 jsBin 演示此方法

You should have the data all contained in some service that notifies any listeners when it is changed. Edit Here is a jsBin demonstrating this method

观察者模式对这个有好处:

The observer pattern would be good for this one:

app.factory('MapService', function() {
  var observerCallbacks = [];
  var markers = [];

  var publicMembers = {
    addMarker: addMarker,
    getMarkers: getMarkers,
    registerObserverCallback: registerObserverCallback
  }

  function addMarker (marker) {
     markers.push(marker);
     notifyObservers();
  };

  function getMarkers() {
     return markers;
  }

  function registerObserverCallback(callback){
    observerCallbacks.push(callback);
  };

  function notifyObservers(){
    angular.forEach(observerCallbacks, function(callback){
      callback();
    });
  };

  return publicMembers;
});

然后在您的控制器中,您可以注入此服务,注册为观察者,并且任何时候通知观察者(例如,在 addMarker 中,您的回调将被执行:

And then in your controller you can can inject this service, register as an observer, and any time observers are notified (e.g., in addMarker, your callback will be executed:

app.controller('MyController', function($scope, MapService) {
    MapService.registerObserverCallback(function() {
        $scope.markers = MapService.getMarkers();
    });
});

这篇关于我应该如何处理控制器之间的函数调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆