Home > Web Front-end > JS Tutorial > Angularjs allows controllers to communicate with each other (code attached)

Angularjs allows controllers to communicate with each other (code attached)

php中世界最好的语言
Release: 2018-05-03 10:57:51
Original
1179 people have browsed it

This time I will bring you AngularjsLet controllers communicate with each other (with code), Angularjs allows controllers to communicate with each otherNotesWhat are they? Here are actual cases. 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:

jQuery implements automatic addition of ellipsis when the input text exceeds the specified number of lines

WeChat applet sharing page Then jump back to the homepage

The above is the detailed content of Angularjs allows controllers to communicate with each other (code attached). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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