Reputation: 835
I'm working with Angular(1.x) and just encountered a strange behaviour (which I do not exclude being a result of my code).
Here is the setup:
var module = angular.module('module_name');
module.service('service_name', function() {
this.function_name = function() { ... }
});
module.controller('controller_name', ['$scope', 'service_name',
function($scope, service_name) {
$scope.function_name = function() { ... }
}])
And in the view :
<div ng-controller='controller_name'>
<button ng-click="function_name()">Test</button>
</div>
The function in service_name is accessible in the controller via service_name.function_name() as expected. But here is the strange behaviour, (once again it occurs in a more complex setting, not saying this portion of code will reproduce the described scenario)
When clicking the button in the view the function called is not the function_name from the controller but the function_name from the service.
Eventhough they have the same name how can the view access a function directly in the service, shouldn't it be limited to its controller scope ?
Upvotes: 1
Views: 504
Reputation: 377
If you do not want to redefine the function name in your controller you can do something like this.
module.service('service_name', function() {
this.function_name = function() { ... }
return {
function_name : function_name
}
});
module.controller('controller_name', ['$scope', 'service_name',
function($scope, service_name) {
$scope.utils = service_name;
}]);
and then in your view call the function directly.
<div ng-controller='controller_name'>
<button ng-click="utils.function_name()">Test</button>
</div>
That's it.
Upvotes: 0
Reputation: 1717
This simply can not happen unless and until somewhere in your code you write
$scope.function_name = service_name.function_name
Services do not have any local scope.In angular view side on-click event expects function in controller's (read local) scope.
What I suspect in your case is , As JS is all reference, You must be doing something like this in large file :
var dummy = service_name.function_name
...
$scope.function_name = dummy
Upvotes: 2
Reputation: 176
It is better to give your controller and service name using for example
abcCtrl
for controller and abcService
for service and so on.
Why, because it will be easier for you to call it. and its not confusing
Upvotes: -1