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

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

问题描述

我想建立一个角度应用程序,由一个全屏地图和一个侧边栏。

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函数调用addMarker使用在广播服务被称为addMarker另一个函数$ rootScope $广播('addMarker');。其中MapController监听,然后调用在MapControlleraddMarker,这实际上增加了标记到地图上。

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 ,您的回调将被执行

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

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

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