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

前端 未结 19 2443
猫巷女王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:52

    This is how I do it with Factory / Services and simple dependency injection (DI).

    myApp = angular.module('myApp', [])
    
    # PeopleService holds the "data".
    angular.module('myApp').factory 'PeopleService', ()->
      [
        {name: "Jack"}
      ]
    
    # Controller where PeopleService is injected
    angular.module('myApp').controller 'PersonFormCtrl', ['$scope','PeopleService', ($scope, PeopleService)->
      $scope.people = PeopleService
      $scope.person = {} 
    
      $scope.add = (person)->
        # Simply push some data to service
        PeopleService.push angular.copy(person)
    ]
    
    # ... and again consume it in another controller somewhere...
    angular.module('myApp').controller 'PeopleListCtrl', ['$scope','PeopleService', ($scope, PeopleService)->
      $scope.people = PeopleService
    ]
    

提交回复
热议问题