How to use an angular service into an non-angular object [duplicate] - angularjs

This question already has answers here:
Call AngularJS from legacy code
(7 answers)
Closed 9 years ago.
I have an angular service
app.factory('MyService', function($http,$q)){
return{
super : function(){
return "Angular is awesome";
}
};
});
and a complex javascript object defined outside Angular's scope (controller or service):
var MyObject = {
anyFunction : function(){
alert(MyService.super());
}
};
Now, doing
MyObject.anyFunction();
of course fails. Any idea how I can get MyService injected into my external javascript object?

This is bad way, byt you may save your angular's var to the localStorage and then acces it from legacy code, and as a second option, you may access global variable from factory, using $window service.
In common js:
var myVar;
In factory:
app.factory('MyService', ['$window', '$http', '$q',function($window, $http, $q)){
return{
super : function(){
$window.myVar = 'that is it';
//or
//localStorage.addItem('myVar', 'varValue');
}
};
}]);
after MyService.super is done, you may access var in common js as usualy before

Related

AngularJS: Why people prefer factory to share data between controllers [duplicate]

This question already has answers here:
AngularJS: Service vs provider vs factory
(30 answers)
Closed 5 years ago.
i am new in angular. so trying to know how to share data between two controller and search google. i visited few pages and found most of the time people use factory to share data. i just like to know can't we do it by service instead of factory ?
1st example
<div ng-controller="FirstCtrl">
<input type="text" ng-model="data.firstName">
<br>Input is : <strong>{{data.firstName}}</strong>
</div>
<hr>
<div ng-controller="SecondCtrl">
Input should also be here: {{data.firstName}}
</div>
myApp.factory('MyService', function(){
return {
data: {
firstName: '',
lastName: ''
},
update: function(first, last) {
// Improve this method as needed
this.data.firstName = first;
this.data.lastName = last;
}
};
});
// Your controller can use the service's update method
myApp.controller('SecondCtrl', function($scope, MyService){
$scope.data = MyService.data;
$scope.updateData = function(first, last) {
MyService.update(first, last);
}
});
2nd example
var myApp = angular.module('myApp', []);
myApp.factory('Data', function(){
var service = {
FirstName: '',
setFirstName: function(name) {
// this is the trick to sync the data
// so no need for a $watch function
// call this from anywhere when you need to update FirstName
angular.copy(name, service.FirstName);
}
};
return service;
});
// Step 1 Controller
myApp.controller('FirstCtrl', function( $scope, Data ){
});
// Step 2 Controller
myApp.controller('SecondCtrl', function( $scope, Data ){
$scope.FirstName = Data.FirstName;
});
examples are taken from this url Share data between AngularJS controllers
please guide me.
Both .service() and .factory() are both singletons as you’ll only get one instance of each Service regardless of what API created it.
Remember that .service() is just a Constructor, it’s called with new, whereas .factory() is just a function that returns a value.
Using .factory() gives us much more power and flexibility, whereas a .service() is essentially the “end result” of a .factory() call. The .service() gives us the returned value by calling new on the function, which can be limiting, whereas a .factory() is one-step before this compile process as we get to choose which pattern to implement and return.

How to pass values from one controller to another controller [duplicate]

This question already has answers here:
Share data between AngularJS controllers
(11 answers)
Closed 6 years ago.
I have
1.) Controller1.js ( which has an array named Arr )
2.) Controller2.js
How should I pass Arr from Controller1.js to Controller2.js?
There are 2 ways to do it, best practice is to create service and store the value in it, and then inject it to both controllers. The angular service is singleton. You can read more here about services.
Second (and not good) way is to use $rootScope.
angular.module('myApp')
.controller('myController1', ['myService', function (myService) {
//myService.array
}])
.controller('myController2', ['myService', function (myService) {
//myService.array
}])
.service('myService', [function () {
var service = {};
service.array = [];
return service
}])

How to inject $rootScope into a service?

how to inject a $rootScope into the factory definition for the following code (so the file can be minified):
(function() {
var signalRService = function($rootScope) {
// ...
};
var app = angular.module("App");
app.factory("signalRService", signalRService);
}());
The way to go about this is by supplying service definition as an array:
var signalRService = ['$rootScope', function($rootScope) {
// ...
}];
Argument will be minifed, but the injector will be based off the string in the array.
That said I'd suggest to revise whether this is really the way to go, as generally speaking relying on $rootScope is inadvisable, and so is using any kind of scopes directly in services/factories.

How to call a function from another controller in AngularJS? [duplicate]

This question already has answers here:
Can one AngularJS controller call another?
(14 answers)
How do I inject a controller into another controller in AngularJS
(7 answers)
Closed 7 years ago.
I need to call a function in another controller in AngularJS. How can I do this?
Code:
app.controller('One', ['$scope',
function($scope) {
$scope.parentmethod = function() {
// task
}
}
]);
app.controller('two', ['$scope',
function($scope) {
$scope.childmethod = function() {
// Here i want to call parentmethod of One controller
}
}
]);
Communication between controllers is done though $emit + $on / $broadcast + $on methods.
So in your case you want to call a method of Controller "One" inside Controller "Two", the correct way to do this is:
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", {});
}
}
]);
While $rootScope.$emit is called, you can send any data as second parameter.
I wouldn't use function from one controller into another. A better approach would be to move the common function to a service and then inject the service in both controllers.
You may use events to provide your data. Code like that:
app.controller('One', ['$scope', function ($scope) {
$scope.parentmethod=function(){
$scope.$emit('one', res);// res - your data
}
}]);
app.controller('two', ['$scope', function ($scope) {
$scope.$on('updateMiniBasket', function (event, data) {
...
});
}]);
If the two controller is nested in One controller.
Then you can simply call:
$scope.parentmethod();
Angular will search for parentmethod function starting with current scope and up until it will reach the rootScope.
The best approach for you to communicate between the two controllers is to use events.
See the scope documentation
In this check out $on, $broadcast and $emit.
If you would like to execute the parent controller's parentmethod function inside a child controller, call it:
$scope.$parent.parentmethod();
You can try it over here

angularjs saving $scope via a closure

Disclaimer that I'm new to angularjs :)
I have a controller that delegates to a service and I'm trying to preserve the $scope so I can scope.apply after setting properties:
var Build = function($scope, $http, mango) {
var scope = $scope;
$scope.BuildManagerSubmit = function(selectedProfile) {
mango.buildMango(selectedProfile.def, function(profiledef) {
// bunch of property assignments on selectedProfile ...
scope.$apply();
}, scope);
};
};
controllers.controller('Build', ['$scope', '$http', 'mango', Build]);
Notice that I'm using the closure to save the scope and passing it in to the service (omitted for brevity). The service calls me back like cb.call(context, ...) so I maintain access to scope. This is all working fine, but I'm more concerned with whether there's a better idiom. I don't see a lot of examples of maintaining $scope when delegating out to services like this.
EDIT: this application is using node-webkit and the 'mango' service essentially is interacting with the file system to call out to shell scripts, etc.
I would make the mango service take care of that (inject $rootScope in it), and perhaps use promises to replace callbacks so it would look like that:
var Build = function($scope, $http, mango) {
$scope.BuildManagerSubmit = function(selectedProfile) {
selectedProfile.profileDef = mango.buildMango(selectedProfile.def);
// do something when profileDef returned? (not always necessary)
selectedProfile.profileDef.then(function(profileDef) {
});
};
};
controllers.controller('Build', ['$scope', '$http', 'mango', Build]);

Resources