使用$emit从指令向控制器发送事件。
使用$emit从指令向控制器发送事件。
我试图在指令和控制器之间使用$emit
发送事件以在选定项时发送事件。我有两个组织的更新函数和另一个用于人员的更新函数。 我的指令应该指定应该发出哪个事件。
这是我的更新函数:
// 对于组织
$scope.updateOrgs = function(selectedVal) { }
// 对于人员
$scope.updatepeople = function(selectedVal, type) { }
当选择人员时,我的指令应该引发updatepeople()
的发射事件,如果是组织,则应该引发updateorg()
。
我的指令如下:
.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片段
如何才能做到这两个函数在不同的控制器中,同时我还需要使用$emit
从指令向控制器发送参数?
admin 更改状态以发布 2023年5月23日
我猜你的其他控制器不是父控制器,所以看看使用$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: '' }; });
ORGS: {{ selectedOrgs }} PEOPLE: {{ selectedPeople }}