I have a working solution in this plunker that addresses various use cases.
The function mentioned will take a parameter with the same name across different scopes.
<body ng-app="MyApp">
<div ng-controller="mainCtrl">
<button ng-click="announce(specificName)">announce in main</button>
<div ng-controller="subCtrl">
<button ng-click="announce(specificName)">announce in sub</button>
</div>
</div>
</body>
Your main controller structure should resemble this:
angular.module('MyApp').controller('mainCtrl', function($scope, ItemService){
$scope.specificName = "I'm main !";
$scope.announce = function(specificName){
alert(specificName);
}
});
You can then override the "specificName" variable in the sub controller:
angular.module('MyApp').controller('subCtrl', function($scope, ItemService){
$scope.specificName = "I'm a sub !";
});
To call the function in pure JS, you can do the following in each controller:
$scope.announce($scope.specificName);
UPDATE :
An alternative solution that may suit your requirements is using a factory or service to share the function.
This is how the service would be structured:
myApp.service("AnnounceService",
function(){
var service = {};
service.announce = function(toAnnounce){
alert(toAnnounce);
}
return service;
}
);
Your controller implementation would be like this:
angular.module('MyApp').controller('subCtrl', function($scope, AnnounceService){
$scope.announce = AnnounceService.announce;
$scope.specificName = "I'm a sub !";
//Equivalent
$scope.announce($scope.specificName);
AnnounceService.announce($scope.specificName);
});
Although you still need to declare specificName in each controller and pass it to the function, the function will now be accessible across your application. Simply inject the service and use it.
Additional Information :
Generally, the key factor to consider is not the function itself but the naming of your variable in each controller. It's advisable to follow a conventional naming approach.
If the variable is related to the state, you can include it in the state definition (I can provide an example if needed).
Lastly, avoid passing complete $scope objects to one another as it is not recommended practice in Angular.
I hope this solution resolves your issue or provides valuable insights. Feel free to ask for more specific details, and I will adjust the answer to suit your requirements.