call a method and send value from controller1 to controller2 in AngularJS - angularjs

based on this reply link I tried to send a data when I click on a button and call a method from Controller1 to Controller2
this is my try:
Controller1:
$scope.DetailsLivraison = function(){
var idv = $scope.idBonSortie;
$rootScope.$emit("CallParentMethod", idv);
}
Controller2:
$rootScope.$on("CallParentMethod", function(){
$scope.parentmethod(idv);
});
$scope.parentmethod = function(idv) {
//Data traitment
}
my problem is that,the method in the second controller is not called,I have defined $rootscope in both controllers
any help please to solve the problem
thanks for help

Firstly, to make this happen both your controllers should be active at that time.
Secondly, you can use the code below:
$rootScope.$broadcast('CallParentMethod', { //can also use $emit
idv: idv,
});
At the receiving end in the other controller:
$rootScope.$on('CallParentMethod', function(event, args) {
$scope.parentmethod(args.idv);
});

Related

how to make $scope.$broadcast work in Ipad?

I have two controllers, say controller1 and controller2.
I have function called function1 defined in controller1.
When I try to call function1 from controller2 using $scope.$broadcast, it works fine in desktop browsers.
But it does not enter into $scope.$on which is written in controller1 in Ipad browser chrome.
I have tried different ways for this to work. importing controller1 into controller2 and so on. But then variables in the browser does not reflect its values.
$scope.$on in controller1:
$scope.$on("con1function", function(event, activity, action) {
$scope.function1(activity,'dashboard');
})
Controller2:
$scope.con2function = function() {
$scope.$broadcast("con1function",data[0], '');
}
can anyone tell me what is wrong here? Or what is the way in which I can make this work for the Ipad as well.
You can try $rootScope.$broadcast("con1function","Hi there") to broadcast the message and $scope.$on() to recieve it.
If your controllers are not related (as parent or child) then just $scope.broadcast or $scope.emit may not work.
var myApp = angular.module('myApp',[]);
myApp.controller('controller1', function ($scope,$rootScope) {
$scope.sendMessage = function(){
console.log("in sendMessage");
$rootScope.$broadcast("con1function","Hi there")
}
});
myApp.controller('controller2', function ($scope,$rootScope) {
console.log("in controller2");
$scope.$on("con1function", function(event, activity) {
console.log('dashboard',activity);
});
});
Also make sure that required controllers are loaded in your script or HTML.

AngularJS - Inject data to DOM with a constructor

I'm trying to inject data from a controller to the DOM. What is happening is that the only way i can pass data is whit a ng-click that will trigger an event to getBooks() function that is attached to the view by $scope.
But i want to see my info when i load the page and not by an event like click, i think i need some constructor or similar.
Controller
angular.module('helloWorldApp').controller('homeCtrl',['$scope','$http','$location','$log',
function($scope,$http){
$scope.getBooks = function(){
$http.get('http://localhost:3010/api/books').then(function(resp){
$scope.books = resp;
});
}
}
])
View
<div class="home-page">
{{books}}
</div>
Thanks for the Help
angular.module('helloWorldApp').controller('homeCtrl',['$scope','$http','$location','$log',
function($scope,$http){
function init() {
$http.get('http://localhost:3010/api/books').then(function(resp){
$scope.books = resp;
});
}
init();
])
Use a function and call that function in controller

How to make controller wait untill app.run finishes

In my application, I'm getting some data in app.run using $http.get()
The result from this is required to proceed to the controller.
Currently my controller is executing before the completion of this $http.get
How can I make my controller's execute after the execution of $http.get()
app.run(function ($rootScope, $http, $cookies) {
var currentLanguageId = angular.fromJson($cookies.get('mykey')).UserInfo.Country;
$http.get('myurl').then(function (serviceInfo) {
$rootScope.serviceURL = serviceInfo.data.serviceURL;
}, function (error) {
alert('error service info');
});
run can't handle asynchronous work at the moment. See this issue : https://github.com/angular/angular.js/issues/4003
You have multiple solutions for that. You can get your data without Angular and start Angular manually ( How to wait for a promise in a Run block in Angular? )
Or you can use the resolve of your route to do this : AngularJS : Initialize service with asynchronous data
You can use angular scope event. When data is fetched, you can broadcast an event from $rootScope to all controllers and receive this event in target controller.
You may use $rootScope.$broadcast();in the app.run and then use $rootScope.$on() in your controller.
app.run(function ($rootScope, $http, $cookies) {
var currentLanguageId = angular.fromJson($cookies.get('mykey')).UserInfo.Country;
$http.get('myurl').then(function (serviceInfo) {
$rootScope.serviceURL = serviceInfo.data.serviceURL;
$rootScope.$broadcast('serviceInfoReceived')
}, function (error) {
alert('error service info');
});
});
In your Controller
app.controller ('myCtrl' , function($rootScope) {
$rootScope.$on("serviceInfoReceived", function(){
console.log($rootScope.serviceURL)
});
})
Hope this may help you.
This is an old question, however the $rootScope.$on solution will not always work. It will depend on the timing of the controller registering the listener. The way I have found that works is to set a $rootScope property, and then configure a recursive timeout to wait for it to be set.
function waitForRun() {
if($rootScope.runFinalized){
// do something
} else {
$timeout(waitForRun, 500)
}
}
waitForRun();
and after the last .run block:
.run(function($rootScope) { $rootScope.runFinalized = true; })
Ugly, but it works.

Call controller function from service in angularjs

I am using socket.io to enable chat in my app and i am using a service SocketService to perform all the socket stuff. When a message came then i want to trigger a function of a controller from the service SocketService to make some changes in the UI.
So i want to know that how can i access the function of a controller from the service.
Sample Code:
.service('SocketService', function ($http,$rootScope,$q) {
this.connect = function(){
var socket = io();
socket.on('connect',function(){
// Call a function named 'someFunction' in controller 'ChatController'
});
}
});
This is the sample code for service.
Now the code for controller
.controller('ChatController',function('SocketService',$scope){
$scope.someFunction = function(){
// Some Code Here
}
});
You could achieve this by using angular events $broadcast or $emit.
In your case $broadcast would be helpful,
You need to broadcast your event in $rootscope that can be listen by all the child scopes which has $on with same event name.
CODE
.service('SocketService', function($http, $rootScope, $q) {
this.connect = function() {
var socket = io();
socket.on('connect', function() {
// Call a function named 'someFunction' in controller 'ChatController'
$rootScope.$broadcast('eventFired', {
data: 'something'
});
});
}
});
.controller('ChatController', function('SocketService', $scope) {
$scope.someFunction = function() {
// Some Code Here
}
$scope.$on('eventFired', function(event, data) {
$scope.someFunction();
})
});
Hope this could help you, Thanks.
I know this is an old question, but I have another option. I have a personal bias against $broadcast - it just doesn't feel very 'angularish', I prefer making explicit calls in my code.
So instead of broadcasting to the controller and triggering another digest cycle, I prefer to have the controller register itself to the service, as below. Just be careful not to introduce any circular dependencies if the controller makes use of the same service. This works best with the controllerAs syntax, so that the calling service does not need to care about $scope.
Yes, this is more code than $broadcast, but it does give the service total access to the entire controller - all of it's methods and properties.
.service('SocketService', function ($http,$rootScope,$q) {
var _this = this;
this.chatController = null;
this.registerCtrlr = function (ctrlr) {
_this.chatController = ctrlr;
};
this.unRegisterCtrlr = function () {
_this.chatController = null;
};
this.connect = function(){
var socket = io();
socket.on('connect',function(){
// Call chatController.someFunction if chatController exists
if (_this.chatController) {
_this.chatController.someFunction();
}
});
};
});
.controller('ChatController',['SocketService', '$scope', function(SocketService, $scope){
SocketService.registerCtrlr(this);
//-- make sure controller unregisters itself when destroyed - need $scope for this
$scope.$on('$destroy', function () {
SocketService.unRegisterCtrlr();
});
this.someFunction = function(){
// Some Code Here
}
}]);
I realize this post is old but I'd like to give my two cents after dealing with Angular JS for several years. I personally would reconsider this approach. Ideally with AngularJS you'd modify your controller/directive to facilitate transferring data to the view model and ultimately bind an HTML template to what I call "the user friendly" view model. This view model should simply reflect what you want the user to see and when in general. Using this method the moment connect event happens your view model which should be bound to the service's data will reflect changes to the data the moment the data arrives.

broadcast is not triggering the on function to pass the data between controller

i am doing a add operation and on result of success i am routing to my main page.Both have respective controllers associated to. I am broadcasting my success message and hope that the on function would recieve the call
carrierFactory.addCarrier(data).then(function(response){
$scope.CarrierDetails.reportSuccessMsg=response.data.reportSuccessMsg;
$rootScope.$broadcast("SuccessMessage", response.data.reportSuccessMsg);
alert(response.data.reportSuccessMsg);
$location.path("/");
Then in the other controller which is assoicated with thr routed page , i am doing
$scope.$on("SuccessMessage", function(event, message) {
$scope.reportSuccessMsg = message;
alert("asdasD");
});
Its not working, so it shoudl be wrong, can you please suggest a better way in doing it. Thanks for help. I am very new to angular.
You should add listener to $rootScope:
$rootScope.$on("SuccessMessage", function(event, message) {
$scope.reportSuccessMsg = message;
alert("asdasD");
});

Resources