This question already has answers here:
How to call a function from another module
(2 answers)
Closed 3 years ago.
I have two angularjs file. I have created some function inside a controller.Now I want to call this function from another module and controller.I tried by injecting the module dependency into my caller module .But it is not recognizing the function.I am new in angularjs.
This is the module I want to call
var app = angular.module("demo", []);
app.controller("testCtrl", function($scope,$http,$window) {
$scope.temp = "";
$scope.rows = []; // init empty array
$scope.datainput =[];
$scope.dataconfig =[];
$scope.myrunner=function(canvasid,inputdata,configdata){
var flag=0;
$scope.datainput=inputdata;
$scope.dataconfig=configdata;
console.log("from base module");
}
$scope.refresh = function(){
location.reload();
}
});
This is the caller module
var app = angular.module("tester", ["demo"]);
app.controller("mycontroller", function($scope) {
var input=[{"status":"PAY_FAIL","value":6248},{"status":"PAY_SUCCESS","value":868},{"status":"PM_REQUESTED","value":11199},{"status":"PAY_INIT","value":992}] ;
var config=[
{"type":"font_name","value":"Calibri"},
{"type":"font_size","value":"25px"}
] ;
$scope.myfn=function(){
demo.myrunner('myCanvas',input,config);
demo.myrunner('myCanvas2',input,config);
}
$scope.myfn();
});
You need to use the factory to communicate between two modules. You cannot have the function inside a controller and call the function from another module.
Example:
var moduleA= angular.module('demo',[]);
moduleA.factory('factoryA', function() {
return {
alertA: function() {
alert('a');
}
};
});
Then use the alertA factory in module B:
angular.module('tester',['A']).controller('mycontroller',function($scope,'factoryA'){
factoryA.alertA();
});
Related
I am trying to bind id from controller1 to one of myservice function.But I get below error
TypeError: _this.dashboardService.chartid is not a function
Please find my code snippet
Service1.js
var Service1 = function (
$http) {
this.$http = $http;
};
Service1.prototype.chartid = function (id) {
return id;
};
appmodule.service('dashboardService', DashboardService);
controller1.js
Controller1.prototype.Chart = function (data) {
_this.service1.chartid(data.key);
};
You haven't inject your service inside your controller, in more classic way:
var controller1=angular.module('controllermodule',[]);
controller1.controller('{name of the controller}',function({service to inject}){}
Javascript prototype functions can be invoked on its objects.When you add prototype you are defining the class whose functions are available on the object.
e.g.
var Service = function() {};
Service.prototype.callMePlease = function() {
console.log('ok Calling now');
return 'Just called';
};
console.log('callMePlease is undefined on Service or is it ? Service.callMePlease='+Service.callMePlease);
var serviceInstance = new Service();
console.log('callMePlease is NOT undefined on serviceInstance or is it ? serviceInstance .callMePlease='+serviceInstance.callMePlease);
var didYouCall = serviceInstance.callMePlease();
console.log('didYouCall='+didYouCall);
Given this you actually need the instance of service1 in your case.
It is best you follow Angular injection model as per official angularjs DI documentation to allow AngularJS create instances for you.
However you may use programattic approach (not advised). In your case
Controller1.prototype.Chart = function (data) {
var myService1 = $injector.get('service1');
myService1.chartid(data.key);
};
When i try to create angularjs module in usual way, it works perfect, but when i try to execute same code inside a callback function of aync function call, it throws error that module not found:
The following code works fine:
var myApp = angular.module('SSApp',[]);
myApp.controller('config', function($scope) {
});
But following throws error:
Init_Data(function() {
initApp();
});
function initApp() {
var myApp = angular.module('SSApp',[]);
myApp.controller('config', function($scope) {
});
}
function Init_Data(callback) {
chrome.storage.local.get(null, function(data) {
window.data = data;
callback();
});
}
I've defined ng-app="SSApp" directive in respective html code.
The reason your code is not doing what you expect is because, Angular tries to bootstrap the module "SSApp" automatically when the DOM is ready. But, finds no such module defined by your JavaScript code when it tries to do so.
You probably have ng-app="SSApp" somewhere in your HTML which is why Angular tries to bootstrap the module automatically.
You can choose to bootstrap the module manually by removing the ng-app directive and doing
angular.bootstrap(document.documentElement, ['SSApp']);
This is the change you have to do:
var myApp = angular.module("SSApp", []);
Init_Data(function () {
initApp();
});
function initApp() {
myApp.controller('config', function ($scope) {
});
console.log(myApp)
}
function Init_Data(callback) {
setTimeout(function () {
callback();
},4000);
}
From what I understand in your code, first you want to load data and then to add config controller to your app...so define your app first and then in your callback configure
I don't know what it is about injecting factories, but I am having the most difficult time.
I've simulated what I'm attempting to do via this sample plunk http://plnkr.co/edit/I6MJRx?p=preview, which creates a kendo treelist - it works fine.
I have an onChange event in script.js which just writes to the console. That's also working.
My plunk loads the following:
1) Inits the app module, and creates the main controller myCtrl (script.js)
2) Injects widgetLinkingFactory int myCtrl
3) Injects MyService into widgetLinkingFactory
The order in which I load the files in index.html appears to be VERY important.
Again, the above plunk is NOT the real application. It demonstrates how I'm injecting factories and services.
My actual code is giving me grief. I'm having much trouble inject factories/services into other factories.
For example,
when debugging inside function linking() below, I can see neither 'CalculatorService' nor 'MyService' services. However, I can see the 'reportsContext' service.
(function () {
// ******************************
// Factory: 'widgetLinkingFactory'
// ******************************
'use strict';
app.factory('widgetLinkingFactory', ['reportsContext', 'MyService', linking]);
function linking(reportsContext, MyService) {
var service = {
linkCharts: linkCharts
};
return service;
function linkCharts(parId, widgets, parentWidgetData) {
// *** WHEN DEBUGGING HERE, ***
// I CANNOT SEE 'CalculatorService' AND 'MyService'
// HOWEVER I CAN SEE 'reportsContext'
if (parentWidgetData.parentObj === undefined) {
// user clicked on root node of grid/treelist
}
_.each(widgets, function (wid) {
if (wid.dataModelOptions.linkedParentWidget) {
// REFRESH HERE...
}
});
}
}
})();
A snippet of reportsContext'service :
(function () {
'use strict';
var app = angular.module('rage');
app.service('reportsContext', ['$http', reportsContext]);
function reportsContext($http) {
this.encodeRageURL = function (sourceURL) {
var encodedURL = sourceURL.replace(/ /g, "%20");
encodedURL = encodedURL.replace(/</g, "%3C");
encodedURL = encodedURL.replace(/>/g, "%3E");
return encodedURL;
}
// SAVE CHART DATA TO LOCAL CACHE
this.saveChartCategoryAxisToLocalStorage = function (data) {
window.localStorage.setItem("chartCategoryAxis", JSON.stringify(data));
}
}
})();
One other point is that in my main directive code, I can a $broadcast event which calls the WidgetLinking factory :
Notice how I'm passing in the widgetLinkingFactory in scope.$on. Is this a problem ?
// Called from my DataModel factory :
$rootScope.$broadcast('refreshLinkedWidgets', id, widgetLinkingFactory, dataModelOptions);
// Watcher setup in my directive code :
scope.$on('refreshLinkedWidgets', function (event, parentWidgetId, widgetLinkingFactory, dataModelOptions) {
widgetLinkingFactory.linkCharts(parentWidgetId, scope.widgets, dataModelOptions);
});
I am wasting a lot of time with these injections, and it's driving me crazy.
Thanks ahead of time for your assistance.
regards,
Bob
I think you might want to read up on factories/services, but the following will work:
var app = angular.module('rage')
app.factory('hi', [function(){
var service = {};
service.sayHi = function(){return 'hi'}
return service;
}];
app.factory('bye', [function(){
var service = {};
service.sayBye = function(){return 'bye'}
return service;
}];
app.factory('combine', ['hi', 'bye', function(hi, bye){
var service = {};
service.sayHi = hi.sayHi;
service.sayBye = bye.sayBye;
return service;
}];
And in controller...
app.controller('test', ['combine', function(combine){
console.log(combine.sayHi());
console.log(combine.sayBye());
}];
So it would be most helpful if you created a plunk or something where we could fork your code and test a fix. Looking over your services it doen't seem that they are returning anything. I typically set up all of my services using the "factory" method as shown below
var app = angular.module('Bret.ApiM', ['ngRoute', 'angularFileUpload']);
app.factory('Bret.Api', ['$http', function ($http: ng.IHttpService) {
var adminService = new Bret.Api($http);
return adminService;
}]);
As you can see I give it a name and define what services it needs and then I create an object that is my service and return it to be consumed by something else. The above syntax is TypeScript which plays very nice with Angular as that is what the Angular team uses.
I have one question about using of services. I'm creating services in this way
and everything working properly. Here is my code.
var appName = angular.module('appName', ['configuration', 'angularSpinner']);
// this is whay that I creating services.
(function (module) {
var moduleName = function () {
return function(inputVar) {
// some work with
// inputVal variable
return result;
}
};
module.factory("moduleName", [moduleName]);
}(angular.module("appName")));
// in this way I'm using service into controller.
appName.controller('controllerName', function($scope, moduleName) {
});
My question is do I need to set 'moduleName' in 'appName'. Ie like this:
var appName = angular.module('appName', ['configuration', 'angularSpinner', 'moduleName']);
In both cases everything works properly. I would appreciate any comments and recommendations.
Best regards.
My question is do I need to set 'moduleName' in 'appName'. Ie like this:
No you do not, unless you actually create another module. In this case your moduleName is actually your factory name. If you wanted to create another module you would do this.
var myModule = angular.module('myModule', []);
myModule.factory('myFactory', [function(){ /* factory definition */ }]);
var app = angular.module('app', ['myModule']);
// this will now make myFactory available to my app
Your using the factory method which returns a function. If you need a service (a singleton object) then use the service method.
I create my services like this
var app = angular.module('app', []);
app.service('myService', [function(){
var serviceMember = { name: 'something' };
var serviceMethod = function() { };
// revealing module pattern
return {
serviceMember: serviceMember,
serviceMethod: serviceMethod
};
}]);
Yes, You needed
var appName = angular.module('appName', ['configuration', 'angularSpinner', 'moduleName'])
The 'appName' is Main Module name, and the 'moduleName' is sub module name. If you put the 'moduleName' with 'appName', then you can call 'modulname' functions wherever you use the 'appName'.
Main Module :
angular.module('appName',
Sub Module :
, ['configuration', 'angularSpinner', 'moduleName']
The concepts works by Dependency Injection Concept
I've created an angular app that has the following structure.
Application configuration, routes, directives, controllers and filters are all defined in index.js (I know this is not recommended). All of my general functions are in a controller called main.js, this is also the controller I am using in my main view in index.html. From then on the app consists of 10 different views, each has it's own controller.
main.js has become very difficult to maintain, so I would like to separate it into five external "utility" style files that contain the general function the application uses. These functions all use angular's $scope and must be able to be accessed by all the views and controllers that exist in the application.
For the past few days I've tried several different methods, such as defining the functions under angular's factory service, using angular's $provide method, defining a controller without a view and many others. None of them worked for me. What is the simplest way to separate the functions that exist in main.js to external js files without changing any code within the functions themselves. Let's pretend that the function cannot be turned into a directive.
Example -
Function that checks users name for 'guest' string and returns an image
main.js -
$scope.defaultpic = function(username) {
var guest = username;
if (guest.indexOf("guest") != -1){
{return {"background-image": "url('data:image/png;base64,chars"}}
}
}
in the view
<img ng-style="defaultpic(JSON.Value)" class="user_pic" ng-src="getprofilepic/{{JSON.Value}}"/>
Cheers,
Gidon
In order to use the function in markup, you still have to bind it to the scope. But, you can move the body of the function to a service:
angular.module('myapp').factory('picService',[ function () {
return {
defaultpic: function(username) {
var guest = username;
if (guest.indexOf("guest") != -1){
{return {"background-image": "url('data:image/png;base64,chars"}}
}
}
};
}]);
And then bind it up in the controller:
$scope.defaultpic = picService.defaultpic;
Refactor controller functions as services declared in different files
As you correctly stated, a great approach to refactor the functions is to put them into different services.
According to the angular Service docs:
Angular services are singletons objects or functions that carry out specific tasks common to web apps.
Here is an example:
Original code
Here we have a simple Hello World app, with a controller that has two functions: greet() and getName().
app.js
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.getName = function () {
return 'World';
}
$scope.greet = function (name) {
return 'Hello ' + name;
};
});
index.html
...
<div id="container" ng-controller="MainCtrl">
<h1>{{greet(getName())}}</h1>
</div>
...
We want to test that our scope always has both functions, so we know it is working as intended, so we are going to write two simple jasmine tests:
appSpec.js
describe('Testing a Hello World controller', function() {
var $scope = null;
var ctrl = null;
//you need to indicate your module in a test
beforeEach(module('plunker'));
beforeEach(inject(function($rootScope, $controller) {
$scope = $rootScope.$new();
ctrl = $controller('MainCtrl', {
$scope: $scope
});
}));
it('should say hallo to the World', function() {
expect($scope.getName()).toEqual('World');
});
it('shuld greet the correct person', function () {
expect($scope.greet('Jon Snow')).toEqual('Hello Jon Snow');
})
});
Check it out in plnkr
Step 1: Refactor controller functions into separate functions
In order to start decoupling our controller to our functions we are going to make two individual functions inside app.js.
app.js
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.getName = getName;
$scope.greet = greet;
});
function getName() {
return 'World';
}
function greet(name) {
return 'Hello ' + name;
}
Now we check our test output and we see that everything is working perfectly.
Check out the plnkr for step 1
Step 2: Move functions to their own services
We will define a NameService and GreetService, put our functions in them and then define the services as dependencies in our controller.
app.js
var app = angular.module('plunker', []);
app.service('NameService', function () {
this.getName = function getName() {
return 'World';
};
});
app.service('GreetService', function() {
this.greet = function greet(name) {
return 'Hello ' + name;
}
});
app.controller('MainCtrl', ['$scope', 'NameService', 'GreetService', function($scope, NameService, GreetService) {
$scope.getName = NameService.getName;
$scope.greet = GreetService.greet;
}]);
We make sure that our tests are still green, so we can move on to the final step.
Have a look at step 2 in plunker
Final Step: Put our services in different files
Finally we will make two files, NameService.js and GreetService.js and put our services in them.
NameService.js
angular.module('plunker').service('NameService', function () {
this.getName = function getName() {
return 'World';
};
});
GreetService.js
angular.module('plunker').service('GreetService', function() {
this.greet = function greet(name) {
return 'Hello ' + name;
}
});
We also need to make sure to add the new scripts to our index.html
index.html
...
<script src="NameService.js"></script>
<script src="GreetService.js"></script>
...
This is how our controller looks like now, neat huh?
app.js
var app = angular.module('plunker', []);
app.controller('MainCtrl', ['$scope', 'NameService', 'GreetService', function($scope, NameService, GreetService) {
$scope.getName = NameService.getName;
$scope.greet = GreetService.greet;
}]);
Plunker for the final step.
And that's it! Our tests still pass, so we know everything works like a charm.