How to share data between controllers in angular app in the right way

前端 未结 3 555
悲哀的现实
悲哀的现实 2021-01-14 10:26

Well, seems that this is not the first question about this subject, but...

I know that we can use service or events for this, but there are many posts on the interne

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-14 10:44

    One way is using scope inheritance:

    angular.module('app', [])
    .run(['$rootScope', function($rootScope){
      $rootScope.sharedObj = {search:''};
    }])
    .controller('navCtr',['$scope',function($scope){
    }])
    .controller('routeCtr',['$scope',function($scope){
      $scope.$watch("sharedObj.search",function(d){
        $scope.data = d ? 'Searched data is ' + d : '';
      });
    }]);
    .main div{
      display:inline-block;
      border:1px solid black;
      height:100px;
      vertical-align: top;
    }
    
    .navigation{
      width: 20%
    }
    .navigation input{
      max-width: 70%;
    }
    
    .page {
      width: 75%
    }
    
    
    
    {{data}}

    the second way would be a shared service:

    angular.module('app', [])
    .factory('srcObject',[function(){
      return {
        value: ''
      }
    }])
    .controller('navCtr',['$scope', 'srcObject', function($scope, srcObject){
      $scope.search = srcObject;
    }])
    .controller('routeCtr',['$scope', 'srcObject', function($scope, srcObject){
      $scope.$watch(function(){return srcObject.value},function(d){
        $scope.data = d ? 'Searched data is ' + d : '';
      });
    }]);
    .main div{
      display:inline-block;
      border:1px solid black;
      height:100px;
      vertical-align: top;
    }
    
    .navigation{
      width: 20%
    }
    .navigation input{
      max-width: 70%;
    }
    
    .page {
      width: 75%
    }
    
    
    
    {{data}}

提交回复
热议问题