我应该如何处理控制器之间的函数调用?

编程入门 行业动态 更新时间:2024-10-28 09:15:16
本文介绍了我应该如何处理控制器之间的函数调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在尝试构建一个包含全屏地图和侧边栏的 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-21 15:08:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1004403.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何处理   控制器   函数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!