问题
I have a service that is injected in my controllers. The service defines a number of functions.
Now I would like to add a variable to that service that would hold the selectedItem in the application. I've done it this way:
angular.module('myservices', []).
factory('serviceA', function () {
var serviceA= {
selectedItem: selectedItem,
... more functions here
};
return serviceA;
var selectedItem;
... functions go here
});
In one of my controllers I set the selected item:
serviceA.selectedItem = someItem;
and in another controller the view references the selected item like this:
<span>{{serviceA.selectedItem.value}}</span>
The span is never updated, even though the selectedItem is set correctly. What am I doing wrong ?
回答1:
To access the service in your view, you need to assign it to the scope:
$scope.serviceA = serviceA;
http://jsfiddle.net/MzJsZ/
回答2:
angular.module('myservices', []).factory('serviceA', function () {
return {
//// factory returns an object
var serviceA= {
selectedItem: selectedItem,
... more functions here
};
return serviceA;
var selectedItem;
... functions go here
}
});
does this work? you were missing the return{} part,where everything goes there. if you would use service you would write just this.serviceA={...}
and your code in controller is missing $scope !
$scope.someItem= serviceA.selectedItem;
or (i dont really know what you want) $scope.serviceA.selectedItem= someItem;
then in your span
<span>{{someItem.value}}</span>
or (i dont really know what you want) <span>{{serviceA.selectedItem.value}}</span>
PS i dont like that your controllers name is the same as object's - serviceA;
回答3:
Ah ! I got it to work !
Doing :
<span>{{serviceA.selectedItem.value}}</span>
in the view wouldn't work because although the serviceA is injected in the view's controller, I did not assign it to the scope... So correct way is to do that in the controller:
angular.module('controllers').controller('someCtrl',
['$scope', 'directDebitService', function ($scope, serviceA) {
$scope.serviceA= serviceA;
}]);
Works fine now.
来源:https://stackoverflow.com/questions/18482488/angularjs-using-service-to-communicate-between-controllers