在 angularjs 中调用另一个控制器下的一个控制器

Call one controller under another controller in angularjs

我想调用LoginController下的Homecontroller。下面是两个控制器的代码:

//Login controller
    app.controller('LoginController', function ($scope, $cookieStore) {
        $cookieStore.put('email','test@gmail.com');
        // need to call Homecontroller here
    });

// Home controller
app.controller('HomeController', function ($scope, $cookieStore, $location) {


      if ($cookieStore.get('email') != null) {
            $scope.wecomeMessage = $cookieStore.get('email');
        }
        else
        {
            $scope.wecomeMessage = "";
        }
    });

我认为您误解了 angular 中控制者的责任。

如何使用 angular 文档中的控制器:

Use controllers to:

  • Set up the initial state of the $scope object.

  • Add behavior to the $scope object.

Do not use controllers to:

  • Manipulate DOM — Controllers should contain only business logic.
  • Putting any presentation logic into Controllers significantly affects its testability.
  • Angular has databinding for most cases and directives to encapsulate manual DOM manipulation.
  • Format input — Use angular form controls instead.
  • Filter output — Use angular filters instead.
  • Share code or state across controllers — Use angular services instead.
  • Manage the life-cycle of other components (for example, to create service instances).

因此,如果您想创建一些可重复使用的代码块,您只需创建一个 angular 服务,该服务将包含具有所需逻辑的功能。然后你可以将它注入到两个控制器,它们将具有必要的功能。

示例:

app.controller('LoginController', function ($scope, $cookieStore, helperService) {
    $cookieStore.put('email', 'test@gmail.com');

    $scope.wecomeMessage = helperService.getMessage();

});

// Home controller
app.controller('HomeController', function ($scope, $cookieStore, $location, helperService) {

    $scope.wecomeMessage = helperService.getMessage();
 });


app.service('helperService', function ($cookieStore) {

    this.getMessage = function () {
        return $cookieStore.get('email') != null ? $cookieStore.get('email') : "";
    };

});