Reputation: 86925
I have a service
and a controller
. How can i define a method inside the service that can be called by the controller (passing a value)?
The following does not work:
angular.module('test').service('myService', function() {
this.updateContent = function(selection) {
alert(selection);
};
return {
//required for some databinding
model: [
someProperty = null;
]
};
});
angular.module('test').controller('testController', ['$scope', 'myService', function($scope, myService) {
$scope.updateSelection = function() {
myService.updateContent("test");
}
}]);
Upvotes: 0
Views: 351
Reputation: 3305
In angularJS, there are some differences between Services and Factories.
When you are using services, you will get an instance of the function that you passed to your service, like a new something()
.
If you are using factories, you will get the value that is returned by the function passed to your factory.
But, all angular Services are Singletons. The Service recipe is almost the same as the Factory recipe, but the injector invokes a constructor with the new
operator instead of a factory function.
Controller
(function(){
function Controller($scope, Service) {
//update by passing 'toto'
Service.update('toto');
//Retrieve object model
console.log(Service.model);
}
angular
.module('app', [])
.controller('ctrl', Controller);
})();
Service
(function(){
function Service() {
var self = this;
self.update = function(value){
console.log(value);
}
self.model = {
test: null
};
}
angular
.module('app')
.service('Service', Service);
})();
Controller
(function(){
function Controller($scope, Factory) {
//update by passing 'toto'
Factory.update('toto');
//Retrieve object model
console.log(Factory.model);
}
angular
.module('app', [])
.controller('ctrl', Controller);
})();
Factory
(function(){
function Factory(){
function update(value){
console.log(value);
}
return {
update: update,
model: {
test: null
}
}
}
angular
.module('app')
.factory('Factory', Factory);
})();
Upvotes: 0
Reputation: 316
You can include the function in the return statement:
return {
//required for some databinding
updateContent: this.updateContent,
model: [
someProperty = null
]
};
Upvotes: 5
Reputation: 38703
Please change testService
to myService
angular.module('test').controller('testController', ['$scope', 'myService', function($scope, myService) {
$scope.updateSelection = function() {
myService.updateContent("test");
}
}]);
Upvotes: 0
Reputation: 9486
angular.module('test').service('myService', function() {
var service = {};
service.model = { prop : null }
service.updateContent = function() {};
return service;
});
Upvotes: 0