AngularJS injecting one module in another module and call function - angularjs

code taken from here http://plnkr.co/edit/jcOwg8HgBGPtod4yCR5j?p=info
i read the below code but still i have confusion that how notifytwo's instance is getting pass to factory notify ?
factory notify has function called sampleFun which call function sampleFunTwo of another factory called notifytwo but i have not found when and how notifytwo's instance is getting pass to factory notify ?
please help me to understand the code flow. thanks
var myModule= angular.module('MyServiceModuleOne', ['MyServiceModuleTwo']);
myModule.controller('TestController', ['$scope', 'notify', function($scope, notify){
$scope.getFn = function() {
notify.sampleFun();
}
}]);
myModule.factory('notify',
function(notifytwo) {
return {
sampleFun: function() {
notifytwo.sampleFunTwo();
},
};
}
);
var myModuleTwo= angular.module('MyServiceModuleTwo',[]);
myModule.factory('notifytwo',
function() {
return {
sampleFunTwo: function() {
alert('From notify two');
}
};
}
);

The notify factory is able to call the factory notifyTwo because notifyTwo is being injected when creating the instance of notify:
myModule.factory('notify',
function(notifytwo) //RIGHT HERE IS WHERE IT'S INJECTED

Related

Auto trigger function throuigh service in angularjs

hi all i am using angulrajs passing one value from one controller to another controller using service it's work fine but my need is when service value change in controller 2 i get the service value in one scope when scope value change i need trigger the function it's called refresh function when service value change and that i need to call the refresh function here my fiddle
https://jsfiddle.net/ctawL4t3/10/
You can just $watch your value.storeObject. Though it's not best of the practices, but it suits this kind of feature.
$scope.$watch('value.storedObject', function(newVal) {
if(newVal !== '') {
refresh()
}
})
working fiddle (open console to see refresh function logging)
You can try to use angular default $emit, $broadcast, or try to do 2 simple functions in own service
angular.module('app').factory('StoreService', function() {
var listeners = {};
var emit = function(name, val) {
if(listeners[name]) {
listeners[name](val)
}
}
var on = function(name, callback) {
listeners[name] = callback;
}
return {
emit: emit,
on: on,
storedObject: ''
};
});
JSFiddle example
JSFiddle example $watch
JSFiddle example ng-change is better because, you can use easily debounce
you can use broadcast function for that
Please check this SO link to find the related answer
How to call a function from another controller in angularjs?
app.controller('One', ['$scope', '$rootScope'
function($scope) {
$rootScope.$on("CallParentMethod", function(){
$scope.parentmethod();
});
$scope.parentmethod = function() {
// task
}
}
]);
app.controller('two', ['$scope', '$rootScope'
function($scope) {
$scope.childmethod = function() {
$rootScope.$emit("CallParentMethod", {});
}
}
]);

Injecting data objects into a directive factory in AngularJS

So I have a directive that takes in data objects as an argument into the scope. The problem is that I handle all my data in my service layer.
So this is some normal non-directive code:
angular.module('app').factory('appFactory', ['appValues', function(appValues) {
var getStuff = function() { return appValues.stuff; };
}]);
But if want to reuse the factory inside a directive and get appValues as an argument:
angular.module('app').directive('myDir', [function() {
return {
...
scope: {
values: '='
}
....
};
}]);
But this puts it on the scope and not into my data layer. So now I need to send the values object to every function call in my directive factory:
angular.module('app').factory('myDirFactory', [function() {
var getStuff = function(values) { return values.stuff; };
}]);
Is there any good pattern to solve this and keep data in the data-layer and bypass the scope/controller?
Also, the factory will be a singleton shared amongst instances of the directive? How should I solve that then? Create a new injector somehow? Submit to putting lots of data object logic into the controller (which I've been thought not to do)?
It was a while ago, and I guess that a simple soultion is simply to provide an function initialize(value) {... return {...};} and then the returned object has access to the value argument without providing it as a parameter everywhere:
angular.module('myDir').factory('myDirFactory', [function() {
var initialize = function(values) {
var getStuff = function() {
return values;
};
return {
getStuff: getstuff;
};
};
return {
initialize: initialize
};
}]);

Can I pass a param from controller into service in AngularJS?

Let's assume I have some service and some controller. What that service will return depends of what the controller will pass into it. But is it possible indeed? I suspect a service may look like this:
var app = angular.module('tApp',[])
.provider('getFileContents', function(param){
this.paramId = param;
this.$get = function(){
var par = this.paramId;
return{
getContents:function(){
return "paramId comes here: "+par;
}
}
}
});
then I think my controller should look like this:
app.controller('test_controlController',
function test_controlController($scope,getFileContents){
$scope.contents = getFileContents.getContents('test_control');
console.dir($scope.contents);
});
...but it doesn't work. It says:
Uncaught Error: Unknown provider: param from tApp
So is it possible to make it working?
You are adding a parameter to the service constructor instead to the service function. and you are using a provider instead of a service or factory, you can get some information about the difference between services/factories and providers here:
Angular Service VS Provider VS Factory
Back to your code, make to following changes:
Service:
app.service('FileService', function () {
return {
getFileContents : function (fileID) {
//function logic goes here
console.log(fileID);
}
}
});
Controller:
app.controller('TestController', function ($scope,getFileContents) {
$scope.contents = getFileContents.getFileContents(123);
});
Add a parameter for your getContents method in your service
return{
getContents:function(foo){
return "paramId comes here: "+ foo;
}
}

Angular and non shared services

I know that angular services are singeltons but I have an application in which I want that each directive instance will have a different service object which will hold context. How can it be achived?
You can use a factory that returns the constructor the class that you need, later just inject it to the controller and instantiate it.
app.factory('demoClass', function() {
return {
sayHello : function() { console.log('hello') }
}
});
At controller:
function myController($scope, demoClass)
{
var test = new demoClass();
test.sayHello();
}

AngularJS : Why is my factory always undefined in my controller?

My factory is undefined in my controller and I cannot figure out why. I have created a simple example to illustrate.
Here I create the app:
var ruleApp = angular
.module( "ruleApp", [
"ngRoute",
"ruleApp.NewFactory1",
"ruleApp.NewFactory2",
] );
In this dummy example I'd like to build a factory that does something simple, show an alert box. I'll show two methods of doing this (one works, one does not).
Factory 1:
angular
.module('ruleApp.NewFactory1', [])
.factory('NewFactory1', function() {
return function(msg) {
alert(msg);
};
});
Factory 2:
angular
.module('ruleApp.NewFactory2', [])
.factory('NewFactory2', function() {
var showMessageFunction = function(msg) {
alert(msg);
};
return
{
showMessage: showMessageFunction
};
});
Notice the return type of factory 1 is a function and the return type of factory 2 is an object with a property (which is of type function).
Now look at how I'd like to use both of these factories in my controller:
ruleApp.controller( "RuleController", function( $scope, NewFactory1, NewFactory2 ) {
NewFactory1("1");
NewFactory2.showMessage("2");
});
This is where the problem gets exposed. During execution, I am prompted with the alert box for NewFactory1("1");, but it fails during execution of NewFactory2.showMessage("2"); because NewFactory2 is undefined (TypeError: Cannot call method 'showMessage' of undefined).
Can you help me spot the issue? I want to be able to use factories like NewFactory2 because I want the factories to be able to do more than just one thing (i.e. have more than one single function). By the way, I'm using Angular version 1.2.1.
factory 2 should be (demo)
angular
.module('ruleApp.NewFactory2', [])
.factory('NewFactory2', function() {
var showMessageFunction = function(msg) {
alert(msg);
};
return { // <--------- do not go on a new line after return
showMessage: showMessageFunction
};
});

Resources