如何在angular js中使用$emit后重新加载数据

how to reload data after used $emit in angular js

本文关键字:新加载 数据 加载 emit angular js      更新时间:2023-09-26

我对angularJs有一些问题。。如何在使用emit后重新初始化scope中的某个变量。示例代码:

$scope.uiConfig = {title: "example"};
$scope.$emit('myCostumCalendar', 'Data to send');
$scope.$on('myCostumCalendar', function () {
  $scope.uiConfig = {title: "new Title"};
});

您在收到带有数据的参数时传递给$的回调:

$scope.$on('myCostumCalendar', function (event, data) {
  // data will store your sent data
  $scope.uiConfig = {title: "new Title"};
});

var myApp = angular.module('myApp',[]);
  myApp.controller('mainEventController', ['$scope', function($scope) {
    $scope.count = 0;
  }]);
  myApp.controller('EventController', ['$scope', function($scope) {
    debugger;  
    $scope.$on('MyEvent', function() {
       debugger;
	
      $scope.count++;
    });
  }]);
<!DOCTYPE HTML>
<html>
	<head>
		<title>Basic on controllers</title>
		<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
		<script src="basiccontroller.js"></script>
	</head>
	<body ng-app="myApp">
	
		<!-- emit and broadcast -->
		<p><b>emit and broadcast</b></p>
		<p>----------------------------</p>
		 <div ng-controller="mainEventController">
		Root scope <tt>MyEvent</tt> count: {{count}}
		<ul>
			<li ng-controller="EventController">
				<button ng-click="$emit('MyEvent')">$emit('MyEvent')</button>
				<button ng-click="$broadcast('MyEvent')">$broadcast('MyEvent')</button>
				<br>
				Middle scope <tt>MyEvent</tt> count: {{count}}
				<ul>
					<li  ng-controller="EventController">
						Leaf scope <tt>MyEvent</tt> count: {{count}}
					</li>
				</ul>
			</li>
		</ul> 
		</div>
		
	</body>
</html>

下面的代码没有给出正确的结果:

继承的scope值不会在$emit函数中给出正确的结果,第一次emit函数也不会像预期的那样在angular js中工作。

请澄清一下。