理想情况下,服务用于在不同的控制器中共享通用方法。回来就好了this
。此外,如果您需要将值返回给控制器,而不是使用事件,为什么不简单地从服务公共方法返回值并访问控制器中的值。此外,控制器的工作是启动或调用服务的方法并更新相应的范围。从服务触发事件以通知控制器类似于什么firing events from one controller to other
。服务不是为此目的而提供的。请参阅我的代码以供参考。
演示 - http://plnkr.co/edit/Co7ka0sZKZgYk5Oz88Np?p=preview
JS:
var app = angular.module('myApp', []);
app.controller('myController', ['$scope', '$rootScope', 'pService', function ($scope, $rootScope, pService) {
$scope.name = 'softvar';
$scope.itemId = pService.Update({LastItemId: 4})
}]);
app.factory('pService', [ '$rootScope', function ( $rootScope) {
this.pService = {};
//Some other code
this.Update= function(status) {
if (status.LastItemId) {
this.pService.disItemId = status.LastItemId;
console.log(this.pService.disItemId)
return this.pService.disItemId;
}
}
//Some other code
return this;
}]);
HTML:
<body ng-app="myApp" ng-controller="myController">
<h1>ItemId is: {{itemId}}!</h1>
</body>
更新:
演示 - http://plnkr.co/edit/Co7ka0sZKZgYk5Oz88Np?p=preview
JS:
var app = angular.module('myApp', []);
app.controller('myController', ['$scope', '$rootScope', 'pService', function ($scope, $rootScope, pService) {
$scope.name = 'softvar';
$scope.$on('serviceUpdated', function (ev, data) {
$scope.itemId = data;
});
pService.Update({LastItemId: 4});
}]);
app.factory('pService', [ '$rootScope', function ( $rootScope) {
this.pService = {};
//Some other code
this.Update= function(status) {
if (status.LastItemId) {
this.pService.disItemId = status.LastItemId;
console.log(this.pService.disItemId)
$rootScope.$broadcast('serviceUpdated', this.pService.disItemId);
}
}
//Some other code
return this;
}]);