答案 0 :(得分:1)
使用broadcast
从另一个控制器调用方法,而不是使用服务。
.controller('ctrl', [
'$scope', 'svc',
function($scope, svc) {
$scope.fun = function() {
$scope.$emit('sampleEvent')
}
}
])
.controller('ctrl1', [
'$scope', 'svc', '$rootScope',
function($scope, svc, $rootScope) {
$rootScope.$on('sampleEvent', function(ev) {
$scope.fun2()
})
$scope.fun2 = function() {
alert("hi");
}
}
]);
答案 1 :(得分:1)
如果你真的想用服务来做,你可以这样做
(function() {
angular.module('app', [])
.service('svc', function() {
var svc = {};
svc.method = function() {
// And here you can call it
svc.fun2();
//on click from first controller it should open a alert box saying "hi"
}
return svc;
})
.controller('ctrl', [
'$scope', 'svc', function($scope, svc) {
$scope.fun = function(){
svc.method();
}
}
])
.controller('ctrl1', [
'$scope', 'svc', function($scope, svc) {
$scope.fun2 = function(){
alert("hi");
}
// inject your method to your service here when method is defined
svc.fun2 = $scope.fun2;
}
]);
})();