我在项目中有两个控制器和两个视图ASP.NET MVC
。我的要求是在ng-click上将数据从一个控制器传递到另一个控制器,该数据应反映在另一个视图中(以及来自另一个控制器)。简单!我知道,可以使用服务来完成,但我更喜欢用于测试目的$broadcast
和$on
。所以我尝试了以下方法:
app.controller('FirstController', function ($rootScope, $scope, productService) {
$scope.showData = function (m) { //This is the event on which I'll get data in another controller as well in another view
alert(m); //This works and gets a name from the first view
$rootScope.$broadcast('sample', $scope.m); //This is what I am using to deliver in another controller
}
});
app.controller('SecondController', function ($scope) {
$scope.$on('sample', function (events, d) {
alert(d);
})
在另一个视图中,我使用了这样的东西:
<div ng-app="app" ng-controller="SecondController">
<ul class="nav navbar-nav">
<li><a href="#"> Product {{ m }}</a></li>
</ul>
</div>
实际上,我这样做都是为了演示目的。但不幸的是,上述方法不起作用。我错过了什么吗?
更新 1 - 请参阅更新的代码:
app.controller('FirstController', function ($rootScope, $scope, productService) {
$scope.showData = function (m) { //This is the event on which I'll get data in another controller as well in another view
alert(m); //This works and gets a name from the first view
$timeout(function () {
$scope.$broadcast('sample', m);
});
}
});
app.controller('SecondController', function ($scope) {
$scope.$on('sample', function (events, d) {
alert(d);
})
在您的方案中,它在一种情况下不起作用:
您之前打电话给$rootScope.$broadcast('sample', $scope.m);
$scope.$on()
已注册以在创建事件之前侦听'sample
事件SecondController
。
如果你知道SecondController
是创建的,你可以用$timeout
来包装$rootScope.$broadcast('sample', $scope.m);
。
$timeout(function(){
$rootScope.$broadcast('sample', $scope.m);
});
在这种情况下$broadcast
执行将被移动到事件队列的末尾,即在下一个摘要周期之前,这将保证已创建第二个控制器并注册$scope.$on()
。
目前还不完全清楚你如何使用第二个视图和控制器。它是否在模板中的某个位置分配了FirstController
?查看分配给FirstController
的模板将有助于澄清。无论如何,我已经附加了一个简单的 plunker,它显示了如何将事件从按钮单击广播到第二个控制器。
https://plnkr.co/edit/KzNftVAYwPuCvsnflIz