Angularjs call a function from a controller to another controller - angularjs

I'm trying since few hours to call a function from a controller to another controller.
I saw similar topics (I tried but I'm certainly too bad):
What's the correct way to communicate between controllers in AngularJS?
Can one controller call another?
But no concrete example like I'm looking for.
Controllers:
app.controller('Controller1', function($scope, $modal, $modalInstance, job, JobServices) {
$scope.job1 = function () {
JobServices.job1($scope.name)
.success(function(data, status, headers, config) {
// something
});
}
function doSomething(){
// How call test() from controller2 ?
}
}
app.controller('Controller2', function($scope){
function test(){
do a lot of things
}
}
What's the best and easiest way to do that ?
Thank you a lot
EDIT:
I already tried using something like that:
app.controller('Controller1', ['$scope', '$rootScope', function($scope, $rootScope, $modal, $modalInstance, job, JobServices) {
But I have error saying job1 is undefined...

you could the $scope.$emit and $scope.$on, little bit like this
app.controller('Controller1', ['$scope', '$rootScope' function($scope) {
function doSomething(){
$rootScope.$emit("callController2", {});
}
}
app.controller('Controller2', ['$scope', '$rootScope' function($scope) {
$rootScope.$on("callController2", function(){
this.test();
});
function test(){
do a lot of things
}
}

Related

how to passing data from one controller to another controller using angular js 1

hi all i using angular js i need to transfer the value from one page controller to another page controller and get that value into an a scope anybody help how to do this
code Page1.html
var app = angular.module("app", ["xeditable", "angularUtils.directives.dirPagination", "ngNotify", "ngCookies","ngRoute"]);
app.controller('Controller1', ['$scope', '$http', '$window', '$filter','$notify','$cookieStore',
function ($scope, $http, $window, $filter, $notify, $cookieStore)
{
$scope.Message="Hi welcome"
}]);
now i want to show scope message into page2 controller
var app = angular.module("app", ["xeditable", "angularUtils.directives.dirPagination", "ngNotify", "ngCookies","ngRoute"]);
app.controller('Controller2', ['$scope', '$http', '$window', '$filter','$notify','$cookieStore',
function ($scope, $http, $window, $filter, $notify, $cookieStore)
{
///here i want get that scope value
}]);
You can use $rootScope instead of $scope:
// do not forget to inject $rootScope as dependency
$rootScope.Message="Hi welcome";
But the best practice is using a service and share data and use it in any controller you want.
You should define a service and write getter/setter functions on this.
angular.module('app').service('msgService', function () {
var message;
this.setMsg = function (msg) {
message = msg;
};
this.getMsg = function () {
return message;
};
});
Now you should use the setMeg function in Controller1 and getMsg function in Controller2 after injecting the dependency like this.
app.controller('Controller1', ['$scope', '$http', '$window', '$filter','$notify','$cookieStore', 'msgService',
function ($scope, $http, $window, $filter, $notify, $cookieStore, msgService)
{
$scope.Message="Hi welcome"
msgService.setMsg($scope.Message);
}]);
app.controller('Controller2', ['$scope', '$http', '$window', '$filter','$notify','$cookieStore', 'msgService',
function ($scope, $http, $window, $filter, $notify, $cookieStore, msgService)
{
///here i want get that scope value
console.log('message from contoller 1 is : ', msgService.getMsg());
}]);
You should use services for it .
Services
app.factory('myService', function() {
var message= [];
return {
set: set,
get: get
}
function set(mes) {
message.push(mes)
}
function get() {
return message;
}
});
And in ctrl
ctrl1
$scope.message1= 'Hi';
myService.set($scope.message1);
ctrl2
var message = myService.get()
Sharing data from one controller to another using service
We can create a service to set and get the data between the controllers and then inject that service in the controller function where we want to use it.
Service :
app.service('setGetData', function() {
var data = '';
getData: function() { return data; },
setData: function(requestData) { data = requestData; }
});
Controllers :
app.controller('Controller1', ['setGetData',function(setGetData) {
// To set the data from the one controller
$scope.Message="Hi welcome";
setGetData.setData($scope.Message);
}]);
app.controller('Controller2', ['setGetData',function(setGetData) {
// To get the data from the another controller
var res = setGetData.getData();
console.log(res); // Hi welcome
}]);
Here, we can see that Controller1 is used for setting the data and Controller2 is used for getting the data. So, we can share the data from one controller to another controller like this.

Can't access my service in my controller (undefined)

I am trying to create a service to do some AJAX requests.
However, my service keeps getting undefined when I try to do something with it in my controllers. Here is my code.
I have found a lot of examples on here, and I've tried to follow a lot of them but no matter what I do my service keeps getting undefined.
My service:
MyApp.factory('myService', function($http) {
return {
findAll: function() {
return $http.get('/findAll')
.then(function(result) {
return result.data;
});
}
}
});
My Controller:
MyApp.controller('UserController', ['$scope', '$http', 'myService', function($scope, $http, $log, myService) {
// Whatever I do with myService here it gets undefined.
//$scope.test = myService.findAll();
//myService.findAll();
}]);
I assume I don't inject it correctly but I can't see whats wrong. I'm fairly new to Angular so..
Any pointers would be appreciated.
Remove $log from the injection. You are currently "naming" the myService service to $log and therefore myService inside the controller is undefined.
MyApp.controller('UserController', ['$scope', '$http', 'myService',
function($scope, $http, myService) {
// Whatever I do with myService here it gets undefined.
//$scope.test = myService.findAll();
//myService.findAll();
}]);
2nd solution
To avoid having to "name" the services like this it's acceptable to inject them without naming them.
MyApp.controller('UserController', function($scope, $http, myService) {
// Whatever I do with myService here it gets undefined.
//$scope.test = myService.findAll();
//myService.findAll();
});
Just remember to remove the closing bracket aswell.

A better way to use filters/objects in Angular controllers?

I'm setting a rootScope variable to maintain the state of the program. This works, but I don't think it's quite 'right'. Is there a better way to select an object from an array?
Here's my current code.
angular.module('myApp.controllers', [])
.controller('packingCtrl', ['$scope', '$http', '$filter', '$rootScope', function($scope, $http, $filter, $rootScope) {
$http.get('data/trayData.json').success(function(data) {
$scope.trays = data;
});
var currentOrder = $rootScope.currentlyPacking;;
$http.get('data/orderData.json').success(function(data) {
$scope.orders = data;
$scope.current = $filter('filter')($scope.orders, {orderId: currentOrder});
});
}])
Thanks in advance for any insight / best practices.
You can create a service to hold your state. Each service instance is a singleton, so when the service is injected into various controllers, all will see the same state.
var currentlyPackingSvc = function($http) {
var currentlyPacking = {
}
return {
currentlyPacking: currentlyPacking,
getTrays: function() { /* make $http call and update currentlyPacking */ },
getOrders: function() { /* make $http call and update currentlyPacking */ }
}
}
angular.service('currentlyPackingSvc', ['$http', currentlyPackingSvc]);
angular.controller('packingCtrl', ['$scope', '$http', '$filter', '$rootScope', 'currentlyPackingSvc'
function($scope, $http, $filter, $rootScope, currentlyPackingSvc) {
...
var currentOrder = currentlyPackingSvc.currentlyPacking;
...
}]);
Assuming you leave your 'currentlyPacking' property as an object, the changes should automatically be pushed to your scope.
This way, you have all your state isolated to one service that can be utilized anywhere.

Injecting $http and $scope into function within controller

I asked a similar question earlier when attempting to inject $scope and $http into a controller Cannot call method 'jsonp' of undefined in Angular.js controller. Now I'm attempting to refactor that code slightly by moving the code into a function within the controller. I'm encountering similar issues and can't seem to grasp the mechanics of dependency injection in Angular. Below is my new code. Both $scope and $http are undefined. What I'm attempting to do is make an http request when didSelectLanguage() fires and assign the resulting data to the "image" variable in the $scope from the parent controller. Can someone enlighten me as to how dependency injection is supposed to work in this example?
angular.module('myApp.controllers', []).
controller('ImagesCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.didSelectLanguage=function($scope, $http) {
console.log($scope);
$http.jsonp('http://localhost:3000/image?quantity=1&language='+this.language+'&Flag=&callback=JSON_CALLBACK')
.success(function(data){
$scope.image = data;
});
}
}])
When you create your controller:
angular.module('myApp.controllers', []).
controller('ImagesCtrl', ['$scope', '$http', function ($scope, $http) {
// ...
}]);
The stuff inside the body of the controller function automatically has access to $scope and $http because of closures. Thus, there's no need to specify anything additional for a function on the $scope to have access to these things:
angular.module('myApp.controllers', []).
controller('ImagesCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.didSelectLanguage = function() {
$http.jsonp('http://localhost:3000/image?quantity=1&language=' + this.language + '&Flag=&callback=JSON_CALLBACK');
.success(function(data) {
$scope.$parent.image = data;
});
}
}]);
When didSelectLanguage is run, it sees the references to $http, and reaches out of the function into the outer function to get the value of the reference; the same happens for $scope inside the success callback.
So, in short, there's no need to pass any arguments to your didSelectLanguage function, nor is there in this case any reason to use the $injector.
With the help of Michelle Tilley's comment & article I solved the problem as follows. However, I'm going to keep the question open until someone else answers or until I understand enough to write an accompanying explanation.
controller('ImagesCtrl', ['$scope', '$http', '$injector', function ($scope, $http, $injector) {
$scope.didSelectLanguage=function() {
$http.jsonp('http://localhost:3000/image?quantity=1&language='+this.language+'&Flag=&callback=JSON_CALLBACK')
.success(function(data){
$scope.$parent.image = data;
});
}
}])

AngularJS, resolve and unknown provider

I've two routes with resolve. Goes like this:
.when('/foos', {
templateUrl: 'views/foos.html',
controller: 'FoosCtrl',
resolve: {
foo_list: ['$q', '$route', '$timeout', '$location', 'Foos', function($q, $route, $timeout, $location, Foos) {
// postpone the execution
var deferred_foo = $q.defer()
Foos.getFoos({token:session_uid}, successCb)
function successCb(list) {
if(list['status'] === 200) {
deferred_foo.resolve(list)
}
else {
alert('Crashcrashcrash')
deferred_foo.reject("Something just wasn't right")
//$location.path('maintenance')
}
}
return deferred_foo.promise
}]
}
})
.when('/r/:type/:bar_id', {
templateUrl: 'views/bar.html',
controller: 'BarsCtrl',
resolve: {
bar: ['$q', '$route', '$timeout', '$location', 'Bars', function($q, $route, $timeout, $location, Bars) {
// postpone the execution
var deferred = $q.defer()
Bars.getBar({type: bar_type}, successCb)
function successCb(result) {
if(result['status'] === 200) {
deferred.resolve(result)
}
else {
alert('Crashcrashcrash')
deferred.reject("Something just wasn't right")
$location.path('foos')
}
return deferred.promise
}]
}
})
Then I've two controllers working like this:
App.controller('FoosCtrl', ['$scope', '$location', 'Foos', 'foo_list', function($scope, $location, Foos, foo_list) {...}
App.controller('BarsCtrl', ['$scope', '$routeParams', '$location', 'Bars', 'bar', 'sharedService', function($scope, $routeParams, $location, Bars, bar, sharedService) {...}
Could somebody explain why Bar works but Foo gives me Error: Unknown provider: foo_listProvider <- foo_list? I've tried replacing foo_list with different name in case camelCasing did something but didn't help.
So, this question was surprisingly similar to my own which I just figured out with help from the folks over at the Angular IRC channel... are you, by chance, setting up your controller though ng-controller? I had:
<div ng-controller="myCtrl">
... when it should have been removed:
<div>
... because I was setting up the controller in the resolve on the router. That's what I was doing and it was causing this very issue. You can see more here:
https://stackoverflow.com/a/18305423/1306982
foo_list <- is the js file for this being loaded in the your html page in a script tag? it just mightbe the case that when you have forgotten to include factory/service/controller and actually have forgotten to include it in a script tag in the index/app html page (or require shims)
Okay just saw your comment and extending the answer here cos its easier to do it here.
Your code where you declare the controller should read like
App.controller('FoosCtrl',
['$scope', '$location', 'Foos', /* comment out foo_list here*/
function($scope, $location, Foos, foo_list /* this remains */) {
...
}
when the route is getting changed things you mention in 'resolve' would get resolved by ui-router. But it the place where you are declaring your FoosCtrl you don't actually have a provider for it to resolve.
Give this a try i had a similar case like this last week.
Just as a heads up, I just had a similar issue which was caused by adding the resolve-variables as a dependency to the controller while not having set up the response funciton in the $stateProvider.state() yet.
Adding the resolve function fixed the missing dependency
(I still don't quite get why - I'd be glad if anyone could share his knowledge in the comments)

Resources