What's the correct way to communicate between controllers in AngularJS?

前端 未结 19 2842
猫巷女王i
猫巷女王i 2020-11-21 22:02

What\'s the correct way to communicate between controllers?

I\'m currently using a horrible fudge involving window:

function StockSubgro         


        
19条回答
  •  庸人自扰
    2020-11-21 22:40

    Using get and set methods within a service you can passing messages between controllers very easily.

    var myApp = angular.module("myApp",[]);
    
    myApp.factory('myFactoryService',function(){
    
    
        var data="";
    
        return{
            setData:function(str){
                data = str;
            },
    
            getData:function(){
                return data;
            }
        }
    
    
    })
    
    
    myApp.controller('FirstController',function($scope,myFactoryService){
        myFactoryService.setData("Im am set in first controller");
    });
    
    
    
    myApp.controller('SecondController',function($scope,myFactoryService){
        $scope.rslt = myFactoryService.getData();
    });
    

    in HTML HTML you can check like this

    {{rslt}}

提交回复
热议问题