Communication between two modules in AngularJs

后端 未结 3 760
盖世英雄少女心
盖世英雄少女心 2021-02-07 14:08

This is rather simple to imagine, but I haven\'t found any resources mentioning what is correct approach to this issue.

I\'d like to broadcast event in one angular

3条回答
  •  误落风尘
    2021-02-07 14:54

    I stumbled about a similar problem. Here is a plunker which show how to solve a problem like this: http://plnkr.co/edit/uk7ODSbgXfzqw0z6x4EH?p=preview

    var app1 = angular.module('App1', []);
    
    app1.controller('App1Controller', function($scope) {
    
        // use this function to send a value to app2
        var sendText = function(newText) {
            angular.element(document.getElementById('app2')).scope().setText(newText);
        };
    
        $scope.$watch('text', function(newText) {
            sendText(newText);
        });
    
        // initial value
        $scope.text = "Some text";
    });
    
    /*
    
     The code above and below do not share any module, service, etc.
    
    */
    
    
    var app2 = angular.module('App2', []);
    app2.controller('App2Controller', function($scope) {
    
        // this function will be called from app1 when text changes
        $scope.setText = function(newText){
            $scope.$apply(function() {
                $scope.text = newText;
            });
        };
    
    });
    

提交回复
热议问题