search
HomeWeb Front-endJS TutorialDetailed explanation of the mutual communication function between controllers in Angularjs

This time I will bring you a detailed explanation of the mutual communication function of Angularjs. What are the precautions for Angularjs to make controllers communicate with each other? The following is a practical case, let's take a look.

In angularjs development projects, communication between controllers, such as parameter transfer and data transfer, is relatively common. Communication between controllers is particularly important. There are two common methods: first, the angular service method; second, the method based on event broadcasting; in addition, there is also the method based on scope inheritance. Let’s talk about the first two methods first:

1. Method based on angular service:

In angular, the service is a single instance. Therefore, an object is generated in the service, and the object can be shared among all controllers using dependency injection. Refer to the following example, the value of the service object is modified in one controller, and the modified value is obtained in another controller:

var app = angular.module('myApp', []);
app.factory('Myservice', function(){
 return {};
});
//定义服务
app.controller('Ctrltest1', function($scope, 'Myservice') {
 $scope.change = function() {
  Myservice.name = $scope.test; //在第一个控制器中为服务对象赋值
 };
});
app.controller('Ctrltst2', function($scope, 'Myservice') {
 $scope.add = function() {
  $scope.name = Myservice.name; //将第一个控制器中为服务对象赋的值传给第二个控制器
 };
});
<p>
  <input>
  </p><p>click me</p>

<p>
 </p><p>my name {{name}}</p>

2. Method based on event broadcast

Based on event broadcasting, you need to use $emit(), $broadcaset() and $emit() Three methods.

1. Emit custom events to the parent scope hierarchy: use the $emit() method, scope.$emit(name,[args,...])

Note: name is the event name, args is 0 or more parameters.

Application scenario: Used by the child page controller to pass parameters to the controller of the parent page.

2. Broadcast custom events to the sub-scope hierarchy:

Application scenarios: Used by the parent page controller to pass parameters to the child page controller or the same Pass parameters between level controllers.

Use the $broadcaset() method, $scope.$broadcaset(name,[args,...])

Note: name is the event name, args is 0 or more parameters.

3. Use a listener to process custom events

In order to handle emitted or broadcast events, you can Use the $on() method. The $on() method will use the following syntax:

$scope.$on(name,listener)

Note: name is the name of the event to be listened to, and the listener parameter is a function that will accept the event as the first parameter, accepting $emit() or $broadcaset()All other parameters passed by the method are used as subsequent parameters. The $on() method is mainly used to monitor changes in events in the $emit() and $broadcaset() methods. For example, if there is any When a variable changes, the $on() method will obtain the change of the variable.

Refer to the following example. If the value of a variable is modified in one controller, the modified value will be heard in another controller and respond according to the modified value.

app.controller('versiontaskCtrl', function WriteTestcaseCtrl($scope, $cookies, $rootScope, $modal, $stateParams, ui, searchVariable, currentuserversions,) {
 $scope.taskId = $cookies['edit_taskId'];
 $scope.versionid = parseInt($cookies['edit_versionId']);
 $scope.versionName = $cookies['edit_versionName'];
 $scope.version = $scope.versionid;
 getuserversions = function () {
  currentuserversions.get(function (res) {
   $scope.versions = res;
  });
 };
 reload = function () {
  getuserversions();
 };
 $scope.changeVersionid = function (v) {
  console.log(v);
  $scope.$broadcast('versionidChange', $scope.versionid); //向其他控制器广播$scope.versionid值的变化。
 };
 reload();
});

The second controller monitors the broadcast event in the first controller:

app.controller('SchemeTaskEditableRowCtrl', function ($scope, $rootScope, $cookies, $filter, $http, $window, $stateParams, basetasksService, schemetasksService, UserService) {
 $scope.taskId = $cookies['edit_taskId'];
 $scope.versionid = $cookies['edit_versionId'];
 $scope.version = $scope.versionid;
 var userid = $rootScope.user.userid;
 $scope.schemetask = [];
 $scope.basetask = [];
 $scope.result = [];
 $scope.$on('versionidChange', function (event, versionid) {
  $scope.versionid = versionid; //监听到$scope.versionid值的变化。然后调用 $scope.schemeTask()和$scope.getUsers()这两个方法
  $scope.schemeTask();
  $scope.getUsers();
 });
 $scope.schemeTask = function () {
  $scope.tasks = [];
  $scope.schemetask = [];
  schemetasksService.get({version: $scope.versionid}, function (res) {
   $scope.schemetask_collection = res.results;
   //console.log($scope.schemetask_collection);
   $scope.schemetask_displayed = [].concat($scope.schemetask_collection);
   var i = 1;
   angular.forEach($scope.schemetask_collection, function (item) {
    item['director'] = "app.writetestitem" + "({taskid:" + item.id + "})";
    item['number'] = i;
    i++;
    $scope.schemetask.push(item);
   });
   $scope.tasks = $scope.schemetask;
  });
 };
 $scope.getUsers = function () {
  UserService.get(function (res) {
   $scope.users = res.results;
   $scope.usersDisplayed = [].concat($scope.users);
   $scope.itemArray = [];
   $scope.userArray = [];
   $scope.names = [];
   angular.forEach($scope.users, function (item) {
    $scope.itemArray.push(item);
    $scope.userArray.push(item.name + item.number);
    var itemname = {'name': item.name, 'number': item.number};
    $scope.names.push(itemname);
   });
   $scope.selected = $scope.users;
  });
 };
});

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to the php Chinese website Other related articles!

Recommended reading:

Convert html string to HTML tag and use

How to change the construction of new() in js The function return value and this point to

The above is the detailed content of Detailed explanation of the mutual communication function between controllers in Angularjs. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Windows 11 上正确校准 Xbox One 控制器的方法Windows 11 上正确校准 Xbox One 控制器的方法Sep 21, 2023 pm 09:09 PM

由于Windows已成为首选的游戏平台,因此确定其面向游戏的功能就显得尤为重要。其中之一是能够在Windows11上校准XboxOne控制器。借助内置的手动校准,您可以摆脱漂移、随机移动或性能问题,并有效地对齐X、Y和Z轴。如果可用选项不起作用,您可以随时使用第三方XboxOne控制器校准工具。让我们来了解一下!如何在Windows11上校准我的Xbox控制器?在继续操作之前,请确保将控制器连接到电脑并更新XboxOne控制器的驱动程序。当您使用它时,还要安装任何可用的固件更新。1.使用Wind

从零开始学习Laravel:控制器方法调用详解从零开始学习Laravel:控制器方法调用详解Mar 10, 2024 pm 05:03 PM

从零开始学习Laravel:控制器方法调用详解在Laravel的开发中,控制器是一个非常重要的概念。控制器起到了连接模型和视图的桥梁作用,负责处理来自路由的请求,并返回相应的数据给视图展示。控制器中的方法可以被路由调用,这篇文章将详细介绍如何编写并调用控制器中的方法,同时会提供具体的代码示例。首先,我们需要创建一个控制器。可以使用Artisan命令行工具来生

php如何使用CodeIgniter4框架?php如何使用CodeIgniter4框架?May 31, 2023 pm 02:51 PM

PHP是一种非常流行的编程语言,而CodeIgniter4是一种常用的PHP框架。在开发Web应用程序时,使用框架是非常有帮助的,它可以加速开发过程、提高代码质量、降低维护成本。本文将介绍如何使用CodeIgniter4框架。安装CodeIgniter4框架CodeIgniter4框架可以从官方网站(https://codeigniter.com/)下载。下

什么叫laravel控制器什么叫laravel控制器Jan 14, 2023 am 11:16 AM

在laravel中,控制器(Controller)是一个类,用于实现一定的功能;控制器能将相关的请求处理逻辑组成一个单独的类。控制器中存放中一些方法,实现一定的功能,通过路由调用控制器,不再使用回调函数;控制器被存放在“app/Http/Controllers”目录中。

2022年最新5款的angularjs教程从入门到精通2022年最新5款的angularjs教程从入门到精通Jun 15, 2017 pm 05:50 PM

Javascript 是一个非常有个性的语言. 无论是从代码的组织, 还是代码的编程范式, 还是面向对象理论都独具一格. 而很早就在争论的Javascript 是不是面向对象语言这个问题, 显然已有答案. 但是, 即使 Javascript 叱咤风云二十年, 如果想要看懂 jQuery, Angularjs, 甚至是 React 等流行框架, 观看《黑马云课堂JavaScript 高级框架设计视频教程》就对了。

Laravel学习指南:控制器方法调用的最佳实践Laravel学习指南:控制器方法调用的最佳实践Mar 11, 2024 am 08:27 AM

在Laravel学习指南中,控制器方法的调用是一个非常重要的主题。控制器扮演着连接路由和模型的桥梁的角色,在应用程序中起着至关重要的作用。本文将介绍控制器方法调用的最佳实践,并提供具体的代码示例帮助读者更好地理解。首先,让我们来了解控制器方法的基本结构。在Laravel中,控制器类通常存放在app/Http/Controllers目录下,每个控制器类包含多个

进程间的五种通信方式是什么进程间的五种通信方式是什么Dec 07, 2020 pm 01:51 PM

进程间的五种通信方式:1、管道,速度慢,容量有限,只有父子进程能通讯;2、FIFO,任何进程间都能通讯,但速度慢;3、消息队列,可以实现消息的随机查询,容量受到系统限制;4、信号量,不能传递复杂消息,只能用来同步;5、共享内存区,指两个或多个进程共享一个给定的存储区。

在Yii框架中使用控制器(Controllers)处理Ajax请求的方法在Yii框架中使用控制器(Controllers)处理Ajax请求的方法Jul 28, 2023 pm 07:37 PM

在Yii框架中,控制器(Controllers)扮演着处理请求的重要角色。除了处理常规的页面请求之外,控制器还可以用于处理Ajax请求。本文将介绍在Yii框架中处理Ajax请求的方法,并提供代码示例。在Yii框架中,处理Ajax请求可以通过以下步骤进行:第一步,创建一个控制器(Controller)类。可以通过继承Yii框架提供的基础控制器类yiiwebCo

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.