Reputation: 3417
I have a code snippet below.
sample.js
(function() {
/*global angular */
'use strict';
angular.module('myapp', ['spinner'])
.controller('myCtrl', ['$scope', '$window', function ($scope, $window ) {
$scope.methodname = function() {
if(something){
/* Doing some operations */
}
};
/* Here I need to define the callme javascript function */
function callme(response){
/* If I call like this, I'm getting error in console. */
}
}]); /* Controller ends here */
/* Creating a new anonymous function to perform some operations */
(function () {
'use strict';
/* Edited */
code.util.myHTTP(url, function (response) {
// Adding response to session storage
callme(response);
}, function () {
// Removing from session storage
});
})();
}());
Here, I can't able to call callme javascript function inside angular controller . I'm getting error in console like
Uncaught ReferenceError: callme is not defined
Is there any way to achieve this?
Edit:
I need to use some controller parameters inside callme function, that's why I'm defining callme function inside controller.
I have run function in my js file already like below
.run(function($rootScope, $log, $window) {
});
How should I append myCtrl here?
Upvotes: 0
Views: 5741
Reputation: 15070
The dirty way
First, if you want to use your your callme
controller function, then you have to expose it. As you wrote it, it's still private. To make it public, just "append" it to your controller's scope (just as you did with scope.methodname
) :
...
$scope.callme = function(){
...
}
..
Then, use this function in a module so that the controller could be reachable :
angular.module('amodule').run(['myCtrl ', function(myCtrl){
myCtrl.callme();
}]);
Another way
The best thing to do is to use a factory as you want to share a service :
angular.module('myapp').factory('myservice', function(){
function callme(){
// TODO : implement the service
}
return {
callme:callme
};
});
Then in a new module, call that method :
angular.module('amodule').run(['myservice ', function(myservice){
myservice.callme();
}]);
If you want to call that service outside angular (as you are wanting to do):
angular.injector(['myservice']).get('callme').call();
Edit :
You can declare inject the service or controller in one run. It will work.
Please, just keep in mind that injecting your controller in your module's run
method is a result of bad design.
Use factories/services to share data/services.
I'm sure that with more code we can help your more.
Upvotes: 1