我如何注入一个控制器到AngularJS另一个控制器

我如何注入一个控制器到AngularJS另一个控制器

本文介绍了我如何注入一个控制器到AngularJS另一个控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的角,并试图找出如何做的事情...

I'm new to Angular and trying to figure out how to do things...

使用AngularJS,我怎么可以注入一个控制器被另一个控制器中使用?

Using AngularJS, how can I inject a controller to be used within another controller?

我有以下片段:

var app = angular.module("testApp", ['']);

app.controller('TestCtrl1', ['$scope', function ($scope) {
    $scope.myMethod = function () {
        console.log("TestCtrl1 - myMethod");
    }
}]);

app.controller('TestCtrl2', ['$scope', 'TestCtrl1', function ($scope, TestCtrl1) {
    TestCtrl1.myMethod();
}]);

当我执行此,我得到的错误:

When I execute this, I get the error:

Error: [$injector:unpr] Unknown provider: TestCtrl1Provider <- TestCtrl1
http://errors.angularjs.org/1.2.21/$injector/unpr?p0=TestCtrl1Provider%20%3C-%20TestCtrl1

应我甚至试图使用另一个控制器内部的控制器,或者我应该做这个服务?

Should I even be trying to use a controller inside of another controller, or should I make this a service?

推荐答案

您需要注入服务实例化另一个控制器内部的控制器。

You need to inject $controller service to instantiate a controller inside another controller.

例如:

app.controller('TestCtrl2', ['$scope', '$controller', function ($scope, $controller) {
   var testCtrl1ViewModel = $scope.$new(); //You need to supply a scope while instantiating.
   //Provide the scope, you can also do $scope.$new(true) in order to create an isolated scope.
   //In this case it is the child scope of this scope.
   $controller('TestCtrl1',{$scope : testCtrl1ViewModel });
   testCtrl1ViewModel.myMethod(); //And call the method on the newScope.
}]);

在任何情况下,你不能叫 TestCtrl1.myMethod(),因为你已经附着在 $范围的方法而不是在控制器实例。

In any case you cannot call TestCtrl1.myMethod() because you have attached the method on the $scope and not on the controller instance.

如果您共享控制器,那么这将永远是好做: -

If you are sharing the controller, then it would always be better to do:-

.controller('TestCtrl1', ['$log', function ($log) {
    this.myMethod = function () {
        $log.debug("TestCtrl1 - myMethod");
    }
}]);

和消费的同时做:

.controller('TestCtrl2', ['$scope', '$controller', function ($scope, $controller) {
     var testCtrl1ViewModel = $controller('TestCtrl1');
     testCtrl1ViewModel.myMethod();
}]);

在第一种情况下真的 $范围是视图模型,而在第二种情况下,控制器实例本身。

In the first case really the $scope is your view model, and in the second case it the controller instance itself.

这篇关于我如何注入一个控制器到AngularJS另一个控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 06:24