简体   繁体   English

AngularJS:不同视图中的控制器之间的通信

[英]AngularJS: Communication between controllers in different views

I have different views each created by a different controller. 我有不同的视图,每个视图都是由不同的控制器创建的。 At a particular time only one of the views is visible. 在特定时间,只有其中一个视图可见。

I want to switch from one view to another view through a function of the controller of the first view and after that I want to call a method of the second view controller. 我想通过第一个视图的控制器的功能从一个视图切换到另一个视图,然后我要调用第二个视图控制器的方法。

My problem is how should I call this method in an angular way? 我的问题是如何以有角度的方式调用此方法?

I know the possiblity using $broadcast and $on but that smells a little bit. 我知道使用$ broadcast和$ on的可能性,但这有点气味。

The other choice ist to find the scope in the dom and calling the method via scope. 另一个选择是在dom中找到范围并通过范围调用方法。 But that is even more ugly. 但这更加丑陋。

What is the best solution? 最好的解决方案是什么?

You can use services to communicate between controllers. 您可以使用服务在控制器之间进行通信。 While you could create a generic shared service to have a central point to subscribe to and broadcast events, services are easier to maintain over time. 虽然您可以创建一个通用的共享服务来拥有一个订阅和广播事件的中心点,但是随着时间的推移,这些服务更易于维护。

You can use Angular Routing 您可以使用角度路由

Check out the documentation. 查看文档。 This is an excerpt from the documentation. 这是该文档的摘录。 You can make links like 您可以建立类似的链接

<a href="#/phones">Link</a>

For the first route and so on. 对于第一条路线,依此类推。

phonecatApp.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/phones', {
        templateUrl: 'partials/phone-list.html',
        controller: 'PhoneListCtrl'
      }).
      when('/phones/:phoneId', {
        templateUrl: 'partials/phone-detail.html',
        controller: 'PhoneDetailCtrl'
      }).
      otherwise({
        redirectTo: '/phones'
      });
  }]);

Okay it is done and simpler as expected. 好的,它已经完成并且比预期的要简单。

The idea is to use a service used in both views (controllers), that contains a 'execution boolean'. 这个想法是使用两个视图(控制器)中使用的服务,其中包含一个“执行布尔值”。

The first view set the boolean to true, the second set a watch on this boolean and therefore is called and can call the desired method. 第一个视图将布尔值设置为true,第二个视图对此布尔值设置了监视,因此被调用并且可以调用所需的方法。

In the service: 在服务中:

trigger: function(name) { model[name] = true; },
setTriggerWatch: function(scope, name, callback) {
    scope.$watch(function value() {
        return model[name];
    }, function listener(newValue, oldValue) {
        if (newValue) {
            callback();
        }
    });
},

In the destination controller: 在目标控制器中:

sessionData.setTriggerWatch($scope, 'createSession', function callCreateSession() {
    _createSession();
});

In the source controller: 在源控制器中:

sessionData.trigger('createSession');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM