我在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
事件 ae 在SecondController
创建之前。
如果您知道SecondController
已创建,则可以$rootScope.$broadcast('sample', $scope.m);
使用$timeout
. ae:
$timeout(function(){
$rootScope.$broadcast('sample', $scope.m);
});
在这种情况下,$broadcast
执行将在下一个摘要周期之前移动到事件队列 ae 的末尾,这将保证第二个控制器已被创建和$scope.$on()
注册。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句