Calling a function from controller1 within controller2 in angularjs - angularjs

I have a controller that updates my awards scope:
Controller 1
.controller("awardController", ['$scope', '$rootScope', 'Restangular', "$q", "$location", "TokenRestangular",
function ($scope, $rootScope, Restangular, $q, $location, TokenRestangular) {
$scope.updateAwardScope = function () {
resource = TokenRestangular.all('award');
resource.getList()
.then(function (awards) {
$scope.awards = awards;
})
}
}])
Controller 2
I have another controller 2 with a click event thats outside of this controllers scope. Is it possible for the controller below to call the $scope.updateAwardScope function from controller 1?
.controller('MainController', function ($rootScope, $scope) {
$scope.updateAwardScopeClick = function () {
// somehow call function from controller 1
}
});

I've found the use of the factory/service pattern to be a very effective way of reusing code in angular applications. For this particular case you could create an AwardFactory, inject it in your controllers and then call the update function. i.e
AwardFactory
myApp.factory('AwardFactory', ['TokenRestangular', function(TokenRestangular.all) {
var factory = {
awards: []
};
factory.update = function() {
resource = TokenRestangular.all('award');
resource.getList().then(function (awards) {
factory.awards = awards;
});
return factory.awards; // You can skip the return if you'd like that
};
return factory;
}]);
YourController
.controller('MainController', function ($rootScope, $scope, AwardFactory) {
$scope.updateAwardScopeClick = function () {
AwardFactory.update();
}
});
Hope it helps!

You can use angular broadcast and receive
Controller1
.controller("awardController", ['$scope', '$rootScope', 'Restangular', "$q", "$location", "TokenRestangular",
function ($scope, $rootScope, Restangular, $q, $location, TokenRestangular) {
$scope.updateAwardScope = function () {
resource = TokenRestangular.all('award');
resource.getList()
.then(function (awards) {
$scope.awards = awards;
$rootScope.broadcast("update.awards");
})
}
}])
Controller 2
.controller('MainController', function ($rootScope, $scope) {
$rootScope.$on('update.awards', function(){
$scope.updateAwardScopeClick();
});
$scope.updateAwardScopeClick = function () {
// somehow call function from controller 1
}
});

Related

Angularjs: Data emitted in service not received by controller

I want data received by the service to be transmitted to the controller but the controller does not receive the data.
Service:
angular.module('dataService', [])
.constant('productCategoryUrl', ' /api/product/categories')
.service('dataService', function ($rootScope, $http, $filter, $rootScope, productCategoryUrl) {
var currentData = {};
var productCategories = [];
return {
setCurrentCategory: function (category, type) {
$rootScope.$broadcast('set-category', currentData);
},
}
})
Controller:
angular.module('jordans')
.controller('productCategoryCtrl', function ($scope, $rootScope, dataService) {
$scope.productCategories = [];
$rootScope.$on('set-category', function (e, args) {
$scope.currentData.category = args.category;
$scope.currentData.type = args.type;
console.log('*******productcategory.currentdata = '
+ JSON.stringify($scope.currentData))
});
}
Why two instances of $rootScope added in service. Removing this should fix the issue
.service('dataService', function ($rootScope, $http, $filter, $rootScope, productCategoryUrl) {
Should be:
service('dataService', function ($http, $filter, $rootScope, productCategoryUrl) {
Question:
Why you are using $broadcast in service. You can directly create
method in service and call it from controller.
Also You need to destroy $rootScope listerner: See this answer:
Working with $scope.$emit and $scope.$on

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 seem to be able to pass data from one controller to another

The issue is that I can't seem to send information from Controller 1 to Controller 2... I have my service that sets/gets data but it isn't working. The actual error that I'm getting is that Controller 1's dataService.getData is not a function... when it works elsewhere.
Service 1 (in its own file)
app.service('dataService', function() {
var data, queried;
return {
setData: function(queryData) {
this.data = queryData;
this.queried = false;
},
getData: function() {
this.queried = true;
return this.data;
}
};
});
Controller 1 (sending information)
app.controller('MyCtrl', ['$scope', '$location', '$state', function($scope, $location, $state, dataService) {
anotherService.functionName(function(err, data) {
// do some things here
actualService.doesntWork(function(err, data) {
if (!err) {
var query = {};
query.someField = data.someField;
dataService.setData(query);
$state.go("go.somewhere.else");
}
});
});
}]);
Controller 2 (getting information)
app.controller('MyCtrl2', ['$scope', '$location', '$state', function($scope, $location, $state, dataService) {
$scope.buttonPressed = function() {
console.log(dataService.getData());
}
}]);
You didn't injected service dataService inside your MyCtrl & MyCtrl2, ensure dependency should be injected before using it.
Controller
app.controller('MyCtrl', ['$scope', '$location', '$state','dataService', //<-added dependency here
function($scope, $location, $state, dataService) {
anotherService.functionName(function(err, data) {
// do some things here
actualService.doesntWork(function(err, data) {
if (!err) {
var query = {};
query.someField = data.someField;
dataService.setData(query);
$state.go("go.somewhere.else");
}
});
});
}]);
Controller2
app.controller('MyCtrl2', ['$scope', '$location', '$state','dataService',//<-added dependency here
function($scope, $location, $state, dataService) {
$scope.buttonPressed = function() {
console.log(dataService.getData());
}
}]);

When I use a service a form on my controller is not known to the scope of the service

I have the following code factory:
angular.module('common')
.factory('_g',
['$http', '$q', '$resource', '$rootScope', '$timeout', '_o', '_u',
function ($http, $q, $resource, $rootScope, $timeout, _o, _u) {
var _init = function ($scope) {
$scope.modalReset = function () {
_modalReset($scope); // << No modalForm appears on this scope
};
};
var _modalReset = function ($scope) {
$scope.modalForm.$setPristine();
};
return {
init: _init,
modalReset: _modalReset
}
In my controller I initialize the service like this at the start of the code:
_g.init($scope);
On my page I have a form:
<form class="form" name="modalForm">
<button data-ng-click="modalReset()">
Reset
</button>
From what I learned this form will be added to the scope dynamically and appear as $scope.modalForm
When my form calls $scope.modalReset it executes BUT there is no modalForm on the $scope when I check it with the debugger.
Can someone explain why this is. What it seems like is that the service is being passed the
scope at an early stage before the modalForm has been added. Is this the case and is there a
way that I can solve this problem?
First of all its not good practice to use $scope into factory/service. Services are Singletons.
This logic you can write in directive or controller.
Anyways, from your example I don't see you pass somehow $scope as argument to both methods. I would change factory to:
angular.module('common')
.factory('_g',
['$http', '$q', '$resource', '$rootScope', '$timeout', '_o', '_u',
function ($http, $q, $resource, $rootScope, $timeout, _o, _u) {
var _init = function ($scope) {
$scope.modalReset = function () {
_modalReset($scope); // << No modalForm appears on this scope
};
};
var _modalReset = function ($scope) {
$scope.modalForm.$setPristine();
};
return {
init: function ($scope) {
return _init($scope) ;
},
_modalReset: function ($scope) {
return _init($scope) ;
}
}
}]);

Controller not fetching service data

I have a Service and a Controller. The controller calls a function, getItems() on the Service. The Service returns an array of data.
However, the controller appears to not be receiving this, oddly enough.
Controller:
ItemModule.controller('ItemController', ['$scope', 'ItemService',
function ($scope, ItemService) {
$scope.items = [];
$scope.getItems = function() {
$scope.items = ItemService.getItems();
}
$scope.getItems();
}
]);
Service:
ItemModule.service('ItemService', ['$rootScope', '$http',
function($rootScope, $http) {
this.getItems = function() {
$http.get($rootScope.root + '/products').success(function(data) {
// This prints it out fine to the console
console.log(data);
return data;
});
}
}
]);
What am I doing wrong?
A quick and dirty fix would be like that:
ItemModule.service('ItemService', ['$rootScope', '$http',
function($rootScope, $http) {
return {
getItems : function(scope) {
$http.get($rootScope.root + '/products').success(function(data) {
scope.items = data;
});
}
}
}
]);
and then in your controller just call:
ItemService.getItems($scope);
But if your controller is a part of route (and probably is) it would be much nicer to use resolve (look here).

Resources