$scope.$on function is not running

76 views
Skip to first unread message

Imane Alfaqir

unread,
May 20, 2016, 9:32:43 AM5/20/16
to AngularJS

Hi everybody, I'm trying to use $scope.$on and $rootScope.$broadcast in order to use a variable of a controller function in another controller function. I have already use this for other purpose, so my issue is the $scope.$on function isn't executing, I tried to make alert inside it but I didn't get any alert, I don't know what is the problem. Here is a snippet of my code to illustrate the issue. Thankx for advance :)


    app1.controller('autoCompleteCTRL',function($scope,$rootScope,$http) {
      $scope.$on("myEvent3", function (event, args) {
    alert
(1);
    $scope
.SearchNearPoint= args.value;

    $http
({
    method
: "get",
    url
: "path/to/file.php",
    dataType
: 'json',
   
params: { 'userText': $scope.searchText},
    async
: false

   
}).success(function(data, status, headers, config) {
    $rootScope
.suggestions = data;

   
}).error(function(data, status, headers, config) {

   
});

 
});

app1.controller('BasicCenterController', function($scope, leafletData,$http) {
$scope
.$root.$broadcast("myEvent3", {

        value: startLatLng

   
});

});`



Manish Pal

unread,
May 24, 2016, 5:05:15 AM5/24/16
to AngularJS
Not sure, what $scope.$root is...but if you $broadcast it from $rootScope, your other controller would get it.
in fact won't be a bad idea to do $rootScope.$emit and then other controller listens to $rootScope.$on, that ways the event won't have to go through all the scopes on your page.

Imane Alfaqir

unread,
May 24, 2016, 4:14:20 PM5/24/16
to ang...@googlegroups.com
First thank you for your answer and I'm sorry to be late. This works onlu if I put $rootScope.$on inside function, but if I put it outside doesn't work I don't understand why.

--
You received this message because you are subscribed to a topic in the Google Groups "AngularJS" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/angular/ZA1V1Lswfm8/unsubscribe.
To unsubscribe from this group and all its topics, send an email to angular+u...@googlegroups.com.
To post to this group, send email to ang...@googlegroups.com.
Visit this group at https://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.

Manish Pal

unread,
May 25, 2016, 2:34:13 PM5/25/16
to AngularJS
what do you mean inside the function ?
well, as long as the place where you place it, is able to find the $rootScope, it would work. Needs to be injected in the controller where you would use it from.

Manish Pal

unread,
May 25, 2016, 2:34:16 PM5/25/16
to AngularJS
what do you mean inside the function ?
well, as long as the place where you place it, is able to find the $rootScope, it would work. Needs to be injected in the controller where you would use it from.
Reply all
Reply to author
Forward
0 new messages