javascript 使用 $emit from 指令向控制器发送事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29999407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 11:27:45  来源:igfitidea点击:

Send an event using $emit from directive to controller

javascriptangularjsjavascript-events

提问by gtm

I'm trying to send an event when an item gets selected, from directive to controller using $emit. I've two update functions for organizations and another for people. My directive should specify which event should emit.

我试图在一个项目被选中时发送一个事件,从指令到控制器使用$emit. 我有两个针对组织的更新功能,另一个针对人员。我的指令应该指定应该发出哪个事件。

Here is my update functions

这是我的更新功能

// For organization

// 对于组织

 $scope.updateOrgs = function(selectedVal) {

 }

// For people

// 对于人

$scope.updatepeople = function(selectedVal, type) {

}

When it is people my directive should raise an emit event for updatepeople (), if it was org it should raise updateorg().

当它是人时,我的指令应该为 引发一个发射事件updatepeople (),如果是 org 它应该引发updateorg()

my directive looks like...

我的指令看起来像...

.directive('search', function ($timeout) {
    return {
        restrict: 'AEC',
        scope: {
            model: '=',
            searchobj: '@',
        },
        link: function (scope, elem, attrs, index) {
            scope.handleSelection = function (selectedItem) {
                scope.model = selectedItem;
                scope.searchModel="";
                scope.current = 0;
                scope.selected = true;
                $timeout(function () {
                    scope.onSelectupdate();
                }, 200);
            };
            scope.Delete = function (index) {
                    scope.selectedIndex = index;
                    scope.delete({ index: index });
            };
            scope.Search = function (searchitem,event,searchobj) {
//                   alert('item entered'+name)
                   scope.searching = searchitem;
                   scope.searchobject = searchobj;
                   scope.onSearch({ searchitem: searchitem , searchobj:searchobj}); 
            };
            scope.current = 0;
            scope.selected = true;
            scope.isCurrent = function (index) {
                return scope.current == index;
            };
            scope.setCurrent = function (index) {
                scope.current = index;
            };
        },
        controller: ['$scope','$element','$rootScope','SearchOrg', function($scope,$element,$rootScope,SearchOrg) {
            $scope.searchItem = function(filter,searchobj){
                //alert('search'+searchobj);
                SearchOrg().fetch({'filter': filter, 'searchType': searchobj}).$promise.then(function(value){
                    $scope.searchData = value.data;
                    console.info($scope.searchData);
                },
                function(err) { 
                });
            }
        }],
        templateUrl: TAPPLENT_CONFIG.HTML_ENDPOINT[0] + 'home/genericsearch.html'
    }
});;

HTML snippet

HTML 片段

<search searchobj=“tei-org” selectedItems=“arrayofIds” search-id=”someidtoIdentify”/> 

How can I do this both functions are in different controllers, and also I need to send parameters from directive to the controller using $emit?

我怎样才能做到这两个功能都在不同的控制器中,而且我还需要使用 将参数从指令发送到控制器$emit

采纳答案by DTing

Working with $scope.$emit and $scope.$on

使用 $scope.$emit 和 $scope.$on

I'm guessing that your other controllers are not parents, so look at the second option using $broadcast.

我猜你的其他控制器不是父母,所以看看使用$broadcast.

var app = angular.module('app', []);

app.controller('firstController', function($scope) {
  $scope.selectedOrgs = []
  $scope.$on('updateorgs', function(evt, data) {
    $scope.selectedOrgs.push(data);
  });
});

app.controller('secondController', function($scope) {
  $scope.selectedPeople = []
  $scope.$on('updatepeople', function(evt, data) {
    $scope.selectedPeople.push(data);
  });
});

app.directive('someDirective', function($rootScope) {
  return {
    scope: {},
    link: function(scope) {
      scope.options = [{
        id: 1,
        label: 'org a',
        type: 'org'
      }, {
        id: 2,
        label: 'org b',
        type: 'org'
      }, {
        id: 3,
        label: 'person a',
        type: 'person'
      }, {
        id: 4,
        label: 'person b',
        type: 'person'
      }];
      scope.changed = function() {
        if (scope.selected) {
          var updatetype = scope.selected.type; 
          if (updatetype === 'person') {
            $rootScope.$broadcast('updatepeople', scope.selected);
          } else if (updatetype === 'org') {
            $rootScope.$broadcast('updateorgs', scope.selected);
          }
        }
      };
    },
    template: '<select ng-change="changed()" ng-model="selected" ng-options="option.label for option in options"><option value="">Select</option></select>'
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>

<div ng-app='app'>
  <some-directive></some-directive>
  <div ng-controller='firstController'>
    <div>ORGS:</div>
    <div>
      {{ selectedOrgs }}
    </div>
  </div>
  <div ng-controller='secondController'>
    <div>PEOPLE:</div>
    <div>
      {{ selectedPeople }}
    </div>
  </div>
</div>