Home Web Front-end JS Tutorial Detailed explanation of the mutual communication function between controllers in Angularjs

Detailed explanation of the mutual communication function between controllers in Angularjs

Jun 13, 2018 pm 02:47 PM
angularjs controller way of communication

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; //将第一个控制器中为服务对象赋的值传给第二个控制器
 };
});
Copy after login
<p ng-controller=&#39;Ctrltest1&#39;>
  <input type="text" ng-model="test" />
  <p ng-click="change()">click me</p>
</p>
<p ng-controller=&#39;Ctrltest2&#39;>
 <p ng-click="add()">my name {{name}}</p>
</p>
Copy after login

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();
});
Copy after login

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;
  });
 };
});
Copy after login

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 of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to properly calibrate your Xbox One controller on Windows 11 How to properly calibrate your Xbox One controller on Windows 11 Sep 21, 2023 pm 09:09 PM

Since Windows has become the gaming platform of choice, it's even more important to identify its gaming-oriented features. One of them is the ability to calibrate an Xbox One controller on Windows 11. With built-in manual calibration, you can get rid of drift, random movement, or performance issues and effectively align the X, Y, and Z axes. If the available options don't work, you can always use a third-party Xbox One controller calibration tool. Let’s find out! How do I calibrate my Xbox controller on Windows 11? Before proceeding, make sure you connect your controller to your computer and update your Xbox One controller's drivers. While you're at it, also install any available firmware updates. 1. Use Wind

How to use CodeIgniter4 framework in php? How to use CodeIgniter4 framework in php? May 31, 2023 pm 02:51 PM

PHP is a very popular programming language, and CodeIgniter4 is a commonly used PHP framework. When developing web applications, using frameworks is very helpful. It can speed up the development process, improve code quality, and reduce maintenance costs. This article will introduce how to use the CodeIgniter4 framework. Installing the CodeIgniter4 framework The CodeIgniter4 framework can be downloaded from the official website (https://codeigniter.com/). Down

Learning Laravel from scratch: Detailed explanation of controller method invocation Learning Laravel from scratch: Detailed explanation of controller method invocation Mar 10, 2024 pm 05:03 PM

Learning Laravel from scratch: Detailed explanation of controller method invocation In the development of Laravel, controller is a very important concept. The controller serves as a bridge between the model and the view, responsible for processing requests from routes and returning corresponding data to the view for display. Methods in controllers can be called by routes. This article will introduce in detail how to write and call methods in controllers, and will provide specific code examples. First, we need to create a controller. You can use the Artisan command line tool to create

What is laravel controller What is laravel controller Jan 14, 2023 am 11:16 AM

In laravel, a controller (Controller) is a class used to implement certain functions; the controller can combine related request processing logic into a separate class. Some methods are stored in the controller to implement certain functions. The controller is called through routing, and callback functions are no longer used; the controller is stored in the "app/Http/Controllers" directory.

The latest 5 angularjs tutorials in 2022, from entry to mastery The latest 5 angularjs tutorials in 2022, from entry to mastery Jun 15, 2017 pm 05:50 PM

Javascript is a very unique language. It is unique in terms of the organization of the code, the programming paradigm of the code, and the object-oriented theory. The issue of whether Javascript is an object-oriented language that has been debated for a long time has obviously been There is an answer. However, even though Javascript has been dominant for twenty years, if you want to understand popular frameworks such as jQuery, Angularjs, and even React, just watch the "Black Horse Cloud Classroom JavaScript Advanced Framework Design Video Tutorial".

Laravel Study Guide: Best Practices for Controller Method Calls Laravel Study Guide: Best Practices for Controller Method Calls Mar 11, 2024 am 08:27 AM

In the Laravel learning guide, calling controller methods is a very important topic. Controllers act as a bridge between routing and models and play a vital role in the application. This article will introduce the best practices for controller method calling and provide specific code examples to help readers better understand. First, let's understand the basic structure of controller methods. In Laravel, controller classes are usually stored in the app/Http/Controllers directory. Each controller class contains multiple

Use PHP and AngularJS to build a responsive website to provide a high-quality user experience Use PHP and AngularJS to build a responsive website to provide a high-quality user experience Jun 27, 2023 pm 07:37 PM

In today's information age, websites have become an important tool for people to obtain information and communicate. A responsive website can adapt to various devices and provide users with a high-quality experience, which has become a hot spot in modern website development. This article will introduce how to use PHP and AngularJS to build a responsive website to provide a high-quality user experience. Introduction to PHP PHP is an open source server-side programming language ideal for web development. PHP has many advantages, such as easy to learn, cross-platform, rich tool library, development efficiency

What are the five communication methods between processes? What are the five communication methods between processes? Dec 07, 2020 pm 01:51 PM

Five communication methods between processes: 1. Pipe, which is slow and has limited capacity. Only parent and child processes can communicate; 2. FIFO, which can communicate between any processes, but is slow; 3. Message queue, which can realize random query of messages. , the capacity is limited by the system; 4. Semaphores cannot transmit complex messages and can only be used for synchronization; 5. Shared memory area means that two or more processes share a given storage area.

See all articles