Home >Web Front-end >JS Tutorial >Summary of examples of communication methods between controllers in Angularjs

Summary of examples of communication methods between controllers in Angularjs

亚连
亚连Original
2018-05-28 17:21:261603browse

This article mainly introduces the communication methods between Angularjs controllers. It summarizes and analyzes the common communication methods of AngularJS controllers and related operation precautions in the form of examples. Friends in need can refer to the examples in this article.

Describes how Angularjs implements communication between controllers. Share it with everyone for your reference, the details are as follows:

In development projects using angularjs, communication between controllers, such as parameter transfer and data transfer, are 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 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>

2. Event-based broadcasting method

Based on event broadcasting, you need to use$emit(), $broadcaset() and $emit() are the 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(&#39;versiontaskCtrl&#39;, function WriteTestcaseCtrl($scope, $cookies, $rootScope, $modal, $stateParams, ui, searchVariable, currentuserversions,) {
 $scope.taskId = $cookies[&#39;edit_taskId&#39;];
 $scope.versionid = parseInt($cookies[&#39;edit_versionId&#39;]);
 $scope.versionName = $cookies[&#39;edit_versionName&#39;];
 $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(&#39;versionidChange&#39;, $scope.versionid); //向其他控制器广播$scope.versionid值的变化。
 };
 reload();
});

The second controller listens to the broadcast event in the first controller:

app.controller(&#39;SchemeTaskEditableRowCtrl&#39;, function ($scope, $rootScope, $cookies, $filter, $http, $window, $stateParams, basetasksService, schemetasksService, UserService) {
 $scope.taskId = $cookies[&#39;edit_taskId&#39;];
 $scope.versionid = $cookies[&#39;edit_versionId&#39;];
 $scope.version = $scope.versionid;
 var userid = $rootScope.user.userid;
 $scope.schemetask = [];
 $scope.basetask = [];
 $scope.result = [];
 $scope.$on(&#39;versionidChange&#39;, 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[&#39;director&#39;] = "app.writetestitem" + "({taskid:" + item.id + "})";
    item[&#39;number&#39;] = 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 = {&#39;name&#39;: item.name, &#39;number&#39;: item.number};
    $scope.names.push(itemname);
   });
   $scope.selected = $scope.users;
  });
 };
});

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Jquery specific examples introduce when to use AJAX and where AJAX should be used

jquery and PHP combines to implement AJAX long polling

##Initially understand JavaScript, Ajax, jQuery, and compare the relationship between the three

The above is the detailed content of Summary of examples of communication methods 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