Use $ scope. $ Emit and $ scope. $ On

This translation from: .. Working scope with $ $ $ EMIT and scope ON $

The send the I CAN My How $scopeObject from One Another to a using the Controller .$emitand .$onMethods? How to use .$emitand the .$onmethod $scopeobject is sent from one controller to another controller?

function firstCtrl($scope) {
    $scope.$emit('someEvent', [1,2,3]);
}

function secondCtrl($scope) {
    $scope.$on('someEvent', function(mass) { console.log(mass); });
}

It does not work the way I think it should. It's not like I think of work as. Do How $emitand $onwork? $emitAnd $onhow to work the operation?


#1st Floor

Reference: https://stackoom.com/question/yqdK/ using -scope-emit and -scope-on


#2nd Floor

First of all, parent-child scope relation does matter. First, the scope of the parent-child relationship is indeed very important. You have two possibilities to emit some event : You have two events may be issued:

  • $broadcast- dispatches at The Event Downwards to All Child Scopes, $broadcast- the event is sent down to all the sub-ranges,
  • $emit- Upwards through dispatches at The Event at The scope Hierarchy. $emit- Scheduling events up through the scope hierarchy.

I do not know anything about your controllers (scopes) relation, but there are several options: I know nothing about the controller (range) relationship, but there are several options:

  1. Scope of IF firstCtrlIS at The parent of secondCtrlscope, your code Should Work by Replacing $emitby $broadcastin firstCtrl: If the scope firstCtrlis the parent company of secondCtrlrange, your code should be replaced by the work $emitof $broadcastthe firstCtrl:

     function firstCtrl($scope) { $scope.$broadcast('someEvent', [1,2,3]); } function secondCtrl($scope) { $scope.$on('someEvent', function(event, mass) { console.log(mass); }); } 
  2. Case there IS NO parent an In-Child in the Relation the BETWEEN the Inject your Scopes you CAN $rootScopeINTO the Controller and at The Event to Broadcast at The All Child Scopes (Also IE secondCtrl). If there is no parent-child relationship between your scope, you can $rootScopeinject controller and events broadcast to all sub-ranges (i.e., secondCtrl).

     function firstCtrl($rootScope) { $rootScope.$broadcast('someEvent', [1,2,3]); } 
  3. A finally, the when you need to dispatch to the Controller at The Event from Child Scopes Upwards you CAN use $scope.$emit. Finally, when you need to schedule events in the sub-controller up to range, you can use $scope.$emit. Scope of IF firstCtrlIS The parent of secondCtrlscope: if the firstCtrlrange is firstCtrlthe range of the parent secondCtrl:

     function firstCtrl($scope) { $scope.$on('someEvent', function(event, data) { console.log(data); }); } function secondCtrl($scope) { $scope.$emit('someEvent', [1,2,3]); } 

#3rd floor

You can call a service from your controller that returns a promise and then use it in your controller. You can call returns promised service from the controller, and then use it in the controller. Further use And $emitor $broadcastto Inform OTHER Controllers About IT. , And further use $emitor $broadcastto inform other controllers. In my case, I had to make http calls through my service, so I did something like this: In my case, I had to be http calls through my service, so I made something like this:

function ParentController($scope, testService) {
    testService.getList()
        .then(function(data) {
            $scope.list = testService.list;
        })
        .finally(function() {
            $scope.$emit('listFetched');
        })


    function ChildController($scope, testService) {
        $scope.$on('listFetched', function(event, data) {
            // use the data accordingly
        })
    }

and my service looks like this my service looks like this

    app.service('testService', ['$http', function($http) {

        this.list = [];

        this.getList = function() {
            return $http.get(someUrl)
                .then(function(response) {
                    if (typeof response.data === 'object') {
                        list = response.data.results;

                        return response.data;
                    } else {
                        // invalid response
                        return $q.reject(response.data);
                    }

                }, function(response) {
                    // something went wrong
                    return $q.reject(response.data);
                });

        }

    }])

#4th floor

I would additionally suggest a 4th option as a better alternative to the proposed options by @zbynour. I also recommend that the fourth option as @zbynour propose better alternatives options.

The Use $rootScope.$emitRather Within last $rootScope.$broadcastregardless of trasmitting and Receiving BETWEEN The Relationship Controller. Regardless of the relationship between transmission and reception controller are used $rootScope.$emitinstead $rootScope.$broadcast. That Way, at The Event Remains the WITHIN at The the SET of $rootScope.$$listenerswhereas with $rootScope.$broadcastat The Event propagates to All Children Scopes, MOST of Which by Will Probably not BE in the Listeners of that Event Anyway. In this way, an event held in the $rootScope.$$listenerscollection, use $rootScope.$broadcast, events propagate to all child range, most of which may not be the listener of the event. Of Course, in at The Receiving And the Controller's End you use the Just $rootScope.$on. Of course, in the end, you only need to use the reception controller $rootScope.$on.

For this option you must remember to destroy the controller's rootScope listeners: For this option, you must remember the destruction of the controller rootScope listeners:

var unbindEventHandler = $rootScope.$on('myEvent', myHandler);
$scope.$on('$destroy', function () {
  unbindEventHandler();
});

#5th Floor

This is my function: This is my function:

$rootScope.$emit('setTitle', newVal.full_name);

$rootScope.$on('setTitle', function(event, title) {
    if (scope.item) 
        scope.item.name = title;
    else 
        scope.item = {name: title};
});

#6th floor

<!DOCTYPE html>
<html>

<head>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
var app = angular.module('MyApp',[]);
app.controller('parentCtrl',function($scope){
  $scope.$on('MyEvent',function(event,data){    
    $scope.myData = data;
  });
 });

app.controller('childCtrl',function($scope){
  $scope.fireEvent = function(){ 
  $scope.$emit('MyEvent','Any Data');
  }  
 });
</script>
</head>
<body ng-app="MyApp">
<div ng-controller="parentCtrl" ng-model="myName">

{{myData}}

 <div ng-controller="childCtrl">
   <button ng-click="fireEvent()">Fire Event</button>
 </div>

</div>
</body>
</html>
Original articles published 0 · won praise 73 · views 550 000 +

Guess you like

Origin blog.csdn.net/w36680130/article/details/105357705