Home > Web Front-end > JS Tutorial > body text

Detailed explanation of the mutual communication function between controllers in Angularjs

php中世界最好的语言
Release: 2018-06-13 14:47:34
Original
2038 people have browsed it

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!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template