使用 $emit 和 $on 在 AngularJS 中使用两个控制器

Using $emit and $on to work with two Controllers in AngularJS

本文关键字:两个 控制器 emit on 使用 AngularJS      更新时间:2023-09-26

我想定义CtrlOne(Parent)和CtrlTwo(Child)之间的通信。本主题是定义scope: $scope的解决方案,但我无法执行此操作,因为我正在为我的模式窗口使用服务。

在 CtrlOne 中,我有一个包含项目的表格列表。我从我的服务中获得的项目,它执行 http 请求。当我单击一行时,所选项目将显示在使用 CtrlTwo 的模态窗口中。当我进行更改时,表将自动更新(双向数据绑定)。但是当我单击重置 btn 时,只会清除模态窗口中的表单。

CtrlOne 的视图:

<tr ng-repeat="item in list>
  <td>{{ item.lname }}</td>
  <td>{{ item.fname }}</td>
</tr>

按一:

var arrIndex;
$rootScope.$on('reset', function (evt, item) {
  arrIndex = item.items;
  $log.info('arrIndex:', arrIndex.Id);
  if ($scope.list.indexOf(arrIndex)) {
     $scope.list[arrIndex];
  } else {
     $.log.error('false');
  }
});

Id 在 WebAPI(服务器端)中定义,并将自动递增。

按二:

//reset btn
$scope.reset = function () {
  $scope.selected = angular.copy($scope.copyItem);
  $scope.$emit('reset', { items: $scope.selected });
}
//cancel btn
$scope.cancel = function () {
  $modalInstance.dismiss('cancel');
}

CtrlTwo的视图:

//modal window form
<div class="form-group-sm>
   <input type="text" 
          class="form-control" 
          ng-model="selected.lname" 
          ng-required="true"
   />
   <input type="text" 
          class="form-control" 
          ng-model="selected.fname" 
          ng-required="true"
   />
</div>

我该如何解决这个问题?

我会用服务做所有事情,而忘记事件的广播。您的服务可能是这样的:

angular('myApp').factory('myService', myService);
myService.$inject = ['$http'];
function myService ($http) {
   var items = [];
   var editIndex;
   var editItem = {};
   return {
     init: function() { return $http.get(...); }, //method to initiate the items array
     setEditItem: function(i) { 
        editIndex = i;
        angular.extend(editItem, items[editIndex]); //create shallow copy of the object (replace with angular.copy if needed)
     },
     getEditItem: function() { return items[editIndex]; },
     saveEditItem: function() { angular.extend(items[editIndex], editItem); },
     resetEditItem: function() { angular.extend(editItem, items[editIndex]); }
   };
});

然后在 Controller1 上,您将正常执行所有操作,但在选择时,您还需要从服务调用 setEditItem 方法。

$scope.open = function (index) {
  myService.setEditItem(index);      
  modalService.openDialog();
}

在控制器 2 上,将editItem设置为service.getEditItem()

angular('myApp').controller('MyController2', MyController2);
MyController2.$inject = ['myService'];
function MyController(myService)
{
   var me = this; //I'm using the ControllerAs syntax, inject and assign variables to $scope if you prefer it otherwise
   me.editItem = myService.getEditItem(); //this is an object
   me.resetItem = myService.resetEditItem; //this is a function
   me.saveItem = myService.saveEditItem; //this is a function
}

你正在做$scope.$emit('reset', ...),而你应该在$rootScope上做:

$rootScope.$emit('reset', ...)