AngularJS如何从一个网站运行两个控制器,并让其中一个更改

问题描述 投票:0回答:3

The problem

我正在尝试修改AngularJS网页,并且我将变量存储在控制器中。该控制器绑定到第一个选项卡。我希望能够从第二个选项卡(使用它自己的控制器)访问属于该控制器的变量(并保持循环运行)。当我更改选项卡时,它会丢失第一个控制器的焦点,并在我交换回它时重置变量。

Possible Fix?

让主控制器在所有选项卡上运行,并运行循环并存储所有重要变量。然后让单个选项卡的控制器只访问此控制器中的方法/变量。

javascript angularjs angularjs-routing
3个回答
0
投票

首先有趣的是你为更新变量使用循环的原因? use $watch()

通常,有几种方法可以在角度应用程序之间共享变量。

  1. 您可以使用嵌套控制器并在父控制器中共享变量。你将有$ scope。$ parent.variable但angular会为你做这个,你可以通过$ scope.variable调用它。比所有子控制器都要共享其父变量。 see angular ui router nesting
  2. 有服务来存储共享变量。在这种情况下,每次在任何控制器中发生更改时,您都需要有一些方法来更新服务变量。为此,您可以使用$scope.$watch()方法,并为每个属性更改更新您的服务模型。

就个人而言,我更喜欢第一种方法,因为绑定是以角度完成的,并为您节省一些服务方法所需的代码。

一个控制器的“循环”停止的原因可能是因为控制器的$ digest循环未运行。 see more to understand how $digest cycle actually works


1
投票

为什么不使用服务并在2个控制器中注入此服务?然后,每个控制器都可以访问该服务并共享相同的变量。

也许小提琴可能会有所帮助?


0
投票

$rootScope似乎是最容易解决的问题。添加$ rootScope作为依赖关系,然后将数据分配给它。

东西链接这个:

angular.module('app').controller('Controller1', function($rootScope, $scope) {

  $scope.root = $rootScope;

  // Test data 
  $rootScope.something = $rootScope.something || "really important";

});

angular.module('app').controller('Controller2', function($rootScope, $scope) {

  $scope.root = $rootScope;

  // Test data 
  $rootScope.something = $rootScope.something || "even better!";

});

如果感觉“hacky”,那就好了。这是学习和使用service的一个很好的理由。

'use strict';

/**
 * Simple Service to hold my stuff.
 */

angular.module('app').factory('Stuff', function() {

  // This is the Stuff object.  
  // The factory makes stuff as a service when AngularJS starts up.
  // Whenever you put 'Stuff' as a Dependency, Angular will use the first one it made.
  // So all your controllers share the same Stuff object.
  var stuff = {
    // We're just going to keep one thing.
    justOneThing: null
  };

  // These are example functions.  A getter and a setter
  // You could get stuff.justOneThing directly, or use functions
  // Or write anything you like.
  stuff.set = function(value) {
    return stuff.justOneThing = value;
  };

  stuff.get = function() {
    return stuff.justOneThing;
  }

  // This returns the Stuff object.  I like this pattern for services
  // and use it alot.  It's easy for me to see what the factory made
  // and what the service is doing.  THere's other options!
  return stuff;
});
© www.soinside.com 2019 - 2024. All rights reserved.