热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何将控制器注入AngularJS中的另一个控制器-HowdoIinjectacontrollerintoanothercontrollerinAngularJS

ImnewtoAngularandtryingtofigureouthowtodothings我对角度不太熟悉,也不知道怎么做……UsingAngularJS,

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

我对角度不太熟悉,也不知道怎么做……

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

使用AngularJS,如何在另一个控制器中注入要使用的控制器?

I have the following snippet:

我有以下片段:

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?

我应该尝试在另一个控制器中使用一个控制器,还是应该将其作为服务?

7 个解决方案

#1


129  

If your intention is to get hold of already instantiated controller of another component and that if you are following component/directive based approach you can always require a controller (instance of a component) from a another component that follows a certain hierarchy.

如果您的目的是获得另一个组件的已经实例化的控制器,并且如果您遵循基于组件/指令的方法,您总是可以从遵循一定层次结构的另一个组件中要求一个控制器(组件的实例)。

For example:

例如:

//some container component that provides a wizard and transcludes the page components displayed in a wizard
myModule.component('wizardContainer', {
  ...,
  controller : function WizardController() {
    this.disableNext = function() { 
      //disable next step... some implementation to disable the next button hosted by the wizard
    }
  },
  ...
});

//some child component
myModule.component('onboardingStep', {
 ...,
 controller : function OnboadingStepController(){

    this.$OnInit= function() {
      //.... you can access this.container.disableNext() function
    }

    this.OnChange= function(val) {
      //..say some value has been changed and it is not valid i do not want wizard to enable next button so i call container's disable method i.e
      if(notIsValid(val)){
        this.container.disableNext();
      }
    }
 },
 ...,
 require : {
    container: '^^wizardContainer' //Require a wizard component's controller which exist in its parent hierarchy.
 },
 ...
});

Now the usage of these above components might be something like this:

以上这些组件的用法大概是这样的:



...



 

...


There are many ways you can set up require.

有很多方法可以设置需求。

(no prefix) - Locate the required controller on the current element. Throw an error if not found.

(无前缀)-在当前元素上定位所需的控制器。如果没有发现错误,抛出一个错误。

? - Attempt to locate the required controller or pass null to the link fn if not found.

吗?-试图找到所需的控制器或将null传递给link fn(如果没有找到的话)。

^ - Locate the required controller by searching the element and its parents. Throw an error if not found.

^——定位所需的控制器通过搜索元素及其父母。如果没有发现错误,抛出一个错误。

^^ - Locate the required controller by searching the element's parents. Throw an error if not found.

^ ^ -定位所需的控制器通过搜索元素的父母。如果没有发现错误,抛出一个错误。

?^ - Attempt to locate the required controller by searching the element and its parents or pass null to the link fn if not found.

? ^ -试图定位所需的控制器通过搜索元素及其父母或null传递给链接fn如果没有找到。

?^^ - Attempt to locate the required controller by searching the element's parents, or pass null to the link fn if not found.

? ^ ^,试图找到所需的控制器通过搜索元素的父母,或null传递给链接fn如果没有发现。



Old Answer:

旧的回答:

You need to inject $controller service to instantiate a controller inside another controller. But be aware that this might lead to some design issues. You could always create reusable services that follows Single Responsibility and inject them in the controllers as you need.

您需要注入$controller服务来实例化另一个控制器中的控制器。但是要注意这可能会导致一些设计问题。您可以始终创建遵循单个职责的可重用服务,并根据需要将它们注入控制器中。

Example:

例子:

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.
}]);

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

在任何情况下,您都不能调用TestCtrl1.myMethod(),因为您在$scope上附加了方法,而不是在controller实例上。

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");
    }
}]);

and while consuming do:

虽然消费:

.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.

在第一种情况下,$作用域是视图模型,在第二种情况下是控制器实例本身。

#2


33  

I'd suggest the question you should be asking is how to inject services into controllers. Fat services with skinny controllers is a good rule of thumb, aka just use controllers to glue your service/factory (with the business logic) into your views.

我建议你应该问的问题是如何向控制器注入服务。使用瘦控制器的胖服务是一个很好的经验法则,也就是使用控制器将您的服务/工厂(使用业务逻辑)粘到您的视图中。

Controllers get garbage collected on route changes, so for example, if you use controllers to hold business logic that renders a value, your going to lose state on two pages if the app user clicks the browser back button.

控制器在路径更改时收集垃圾,因此,例如,如果您使用控制器来保存呈现值的业务逻辑,如果应用程序用户单击浏览器后退按钮,您将在两个页面上丢失状态。

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

app.factory('methodFactory', function () {
    return { myMethod: function () {
            console.log("methodFactory - myMethod");
    };
};

app.controller('TestCtrl1', ['$scope', 'methodFactory', function ($scope,methodFactory) {  //Comma was missing here.Now it is corrected.
    $scope.mymethod1 = methodFactory.myMethod();
}]);

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

Here is a working demo of factory injected into two controllers

这是一个工厂注入到两个控制器的工作演示

Also, I'd suggest having a read of this tutorial on services/factories.

另外,我建议您阅读一下关于服务/工厂的教程。

#3


12  

There is no need to import/Inject your controller in JS. You can just inject your controller/nested controller through your HTML.It's worked for me. Like :

不需要在JS中导入/注入控制器。您可以通过HTML注入您的控制器/嵌套控制器。它为我工作。如:

#4


-1  

This works best in my case, where TestCtrl2 has it's own directives.

在我的例子中,这是最有效的,TestCtrl2有它自己的指令。

var testCtrl2 = $controller('TestCtrl2')

This gives me an error saying scopeProvider injection error.

这给了我一个错误,说scopeProvider注入错误。

   var testCtrl1ViewModel = $scope.$new();
   $controller('TestCtrl1',{$scope : testCtrl1ViewModel });
   testCtrl1ViewModel.myMethod(); 

This doesn't really work if you have directives in 'TestCtrl1', that directive actually have a different scope from this one created here. You end up with two instances of 'TestCtrl1'.

如果你在“testctrl - l1”中有指令,那么这个指令实际上与这里创建的这个指令有不同的作用域。最后得到两个'TestCtrl1'实例。

#5


-1  

The best solution:-

最好的解决方案:-

angular.module("myapp").controller("frstCtrl",function($scope){$scope.name="Atul Singh";}).controller("secondCtrl",function($scope){angular.extend(this, $controller('frstCtrl', {$scope:$scope}));console.log($scope);})

// Here you got the first controller call without executing it

//这里你得到了第一个控制器调用,但没有执行它

#6


-1  

you can also use $rootScope to call a function/method of 1st controller from second controller like this,

你也可以使用$rootScope从第二个控制器调用第一个控制器的函数/方法,

.controller('ctrl1', function($rootScope, $scope) {
     $rootScope.methodOf2ndCtrl();
     //Your code here. 
})

.controller('ctrl2', function($rootScope, $scope) {
     $rootScope.methodOf2ndCtrl = function() {
     //Your code here. 
}
})

#7


-2  

use typescript for your coding, because it's object oriented, strictly typed and easy to maintain the code ...

为您的代码使用打字稿,因为它是面向对象的,严格的类型和易于维护的代码……

for more info about typescipt click here

有关排版的更多信息请点击这里

Here one simple example I have created to share data between two controller using Typescript...

这里我创建了一个简单的示例,用于使用Typescript在两个控制器之间共享数据。

module Demo {
//create only one module for single Applicaiton
angular.module('app', []);
//Create a searvie to share the data
export class CommonService {
    sharedData: any;
    constructor() {
        this.sharedData = "send this data to Controller";
    }
}
//add Service to module app
angular.module('app').service('CommonService', CommonService);

//Create One controller for one purpose
export class FirstController {
    dataInCtrl1: any;
    //Don't forget to inject service to access data from service
    static $inject = ['CommonService']
    constructor(private commonService: CommonService) { }
    public getDataFromService() {
        this.dataInCtrl1 = this.commonService.sharedData;
    }
}
//add controller to module app
angular.module('app').controller('FirstController', FirstController);
export class SecondController {
    dataInCtrl2: any;
    static $inject = ['CommonService']
    constructor(private commonService: CommonService) { }
    public getDataFromService() {
        this.dataInCtrl2 = this.commonService.sharedData;
    }
}
angular.module('app').controller('SecondController', SecondController);

}

}


推荐阅读
  • Python正则表达式学习记录及常用方法
    本文记录了学习Python正则表达式的过程,介绍了re模块的常用方法re.search,并解释了rawstring的作用。正则表达式是一种方便检查字符串匹配模式的工具,通过本文的学习可以掌握Python中使用正则表达式的基本方法。 ... [详细]
  • IjustinheritedsomewebpageswhichusesMooTools.IneverusedMooTools.NowIneedtoaddsomef ... [详细]
  • GetWindowLong函数
    今天在看一个代码里头写了GetWindowLong(hwnd,0),我当时就有点费解,靠,上网搜索函数原型说明,死活找不到第 ... [详细]
  • Linux重启网络命令实例及关机和重启示例教程
    本文介绍了Linux系统中重启网络命令的实例,以及使用不同方式关机和重启系统的示例教程。包括使用图形界面和控制台访问系统的方法,以及使用shutdown命令进行系统关机和重启的句法和用法。 ... [详细]
  • Ihavethefollowingonhtml我在html上有以下内容<html><head><scriptsrc..3003_Tes ... [详细]
  • Whatsthedifferencebetweento_aandto_ary?to_a和to_ary有什么区别? ... [详细]
  • Netty源代码分析服务器端启动ServerBootstrap初始化
    本文主要分析了Netty源代码中服务器端启动的过程,包括ServerBootstrap的初始化和相关参数的设置。通过分析NioEventLoopGroup、NioServerSocketChannel、ChannelOption.SO_BACKLOG等关键组件和选项的作用,深入理解Netty服务器端的启动过程。同时,还介绍了LoggingHandler的作用和使用方法,帮助读者更好地理解Netty源代码。 ... [详细]
  • 阿里Treebased Deep Match(TDM) 学习笔记及技术发展回顾
    本文介绍了阿里Treebased Deep Match(TDM)的学习笔记,同时回顾了工业界技术发展的几代演进。从基于统计的启发式规则方法到基于内积模型的向量检索方法,再到引入复杂深度学习模型的下一代匹配技术。文章详细解释了基于统计的启发式规则方法和基于内积模型的向量检索方法的原理和应用,并介绍了TDM的背景和优势。最后,文章提到了向量距离和基于向量聚类的索引结构对于加速匹配效率的作用。本文对于理解TDM的学习过程和了解匹配技术的发展具有重要意义。 ... [详细]
  • 本文介绍了闭包的定义和运转机制,重点解释了闭包如何能够接触外部函数的作用域中的变量。通过词法作用域的查找规则,闭包可以访问外部函数的作用域。同时还提到了闭包的作用和影响。 ... [详细]
  • 向QTextEdit拖放文件的方法及实现步骤
    本文介绍了在使用QTextEdit时如何实现拖放文件的功能,包括相关的方法和实现步骤。通过重写dragEnterEvent和dropEvent函数,并结合QMimeData和QUrl等类,可以轻松实现向QTextEdit拖放文件的功能。详细的代码实现和说明可以参考本文提供的示例代码。 ... [详细]
  • CSS3选择器的使用方法详解,提高Web开发效率和精准度
    本文详细介绍了CSS3新增的选择器方法,包括属性选择器的使用。通过CSS3选择器,可以提高Web开发的效率和精准度,使得查找元素更加方便和快捷。同时,本文还对属性选择器的各种用法进行了详细解释,并给出了相应的代码示例。通过学习本文,读者可以更好地掌握CSS3选择器的使用方法,提升自己的Web开发能力。 ... [详细]
  • android listview OnItemClickListener失效原因
    最近在做listview时发现OnItemClickListener失效的问题,经过查找发现是因为button的原因。不仅listitem中存在button会影响OnItemClickListener事件的失效,还会导致单击后listview每个item的背景改变,使得item中的所有有关焦点的事件都失效。本文给出了一个范例来说明这种情况,并提供了解决方法。 ... [详细]
  • 本文介绍了九度OnlineJudge中的1002题目“Grading”的解决方法。该题目要求设计一个公平的评分过程,将每个考题分配给3个独立的专家,如果他们的评分不一致,则需要请一位裁判做出最终决定。文章详细描述了评分规则,并给出了解决该问题的程序。 ... [详细]
  • 推荐系统遇上深度学习(十七)详解推荐系统中的常用评测指标
    原创:石晓文小小挖掘机2018-06-18笔者是一个痴迷于挖掘数据中的价值的学习人,希望在平日的工作学习中,挖掘数据的价值, ... [详细]
  • 本文介绍了在处理不规则数据时如何使用Python自动提取文本中的时间日期,包括使用dateutil.parser模块统一日期字符串格式和使用datefinder模块提取日期。同时,还介绍了一段使用正则表达式的代码,可以支持中文日期和一些特殊的时间识别,例如'2012年12月12日'、'3小时前'、'在2012/12/13哈哈'等。 ... [详细]
author-avatar
淑月冠廷婷婷
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有