【发布时间】:2017-10-12 10:10:55
【问题描述】:
由于某种原因,第二个控制器没有从服务接收数据。 我正在尝试使用一个服务在两个控制器之间进行通信。
观点:
<div class="btn-wrapper" ng-controller="FirstController">
<a ng-href="" ng-click="doPath()" id="go" class="button">GO!</a>
</div>
FirstController.js:
angular.module('app')
.controller('FirstController', function($scope, sharedService) {
$scope.doPath = sharedService.searchPath;
});
共享服务:
angular.module('myServices', [])
.service('sharedService', function($rootScope) {
this.searchPath = function() {
console.log("I got the service!");
$rootScope.$broadcast('Search', {
data: 'something'
});
}
});
还有 SecondController.js
angular.module('app')
.controller('SecondController', function(sharedService, $scope) {
$scope.$on('Search', function(event, data){
console.log(data);
//this.search(); => I intent to run this function after this
});
});
该事件由视图中的一个按钮调度,该按钮调用doPath() 函数。此函数与服务sharedService 进行通信,并显示消息“我得到了服务”。
但是,应用程序在此停止。 Service 和第二个 Controller 之间使用 $rootScope.$broadcast 的通信似乎没有发生(数据没有显示在控制台上,也没有任何错误)。
我在这里找到了一些解决方案。我已经尝试了所有答案,所以问题不一样,原因仍然无法正常工作。
编辑
ngRoute 在这里(app.js):
angular.module('app', ['ngRoute', 'myServices'])
.config(function($routeProvider){
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'FirstController'
})
.otherwise({
redirectTo: '/'
});
});
【问题讨论】:
-
只是一个想法...您正在向
$rootScope广播,但您的控制器在$scope上有监听器。您是否尝试将$rootScope作为参数传递给控制器定义并将侦听器添加到其中?... -
乍一看,sharedService.searchPath 是一个函数,而您似乎并没有执行它。试试 $scope.doPath = sharedService.searchPath();
-
@David Espino,是的,我试过了。同样的结果...
-
@ruedamanuel 它显示“我得到了服务”,没有任何事件!但它一直停在同一个地方。似乎由于某种原因它没有到达第二个控制器。
标签: javascript angularjs