将数据从一个控制器传递到AngularJS中的另一个控制器

时间:2017-01-16 07:24:26

标签: angularjs

如何将数据从一个控制器传递到另一个控制器?

我读了许多东西,比如使用root Scope,使用服务,使用广播事件等,但似乎没有任何工作。有人可以指导我吗?

2 个答案:

答案 0 :(得分:1)

您可以使用 Service factory在控制器之间共享数据。

<强>样本

&#13;
&#13;
var app = angular.module("clientApp", [])
 app.controller("TestCtrl", 
   function($scope,names) {
     $scope.names =[];
    $scope.save= function(){
      names.add($scope.name);
    }
   
   
   }
  );
  
 app.controller("TestCtrl2", 
   function($scope,names) {   
   
   $scope.getnames = function(){
     $scope.names = names.get();
   }
  }
  );
app.factory('names', function(){
  var names = {};

  names.list = [];

  names.add = function(message){
    names.list.push({message});
  };
  
  names.get = function(){
    return names.list;
  };

  return names;
});
&#13;
<!doctype html>
<html >

<head>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
  <script src="script.js"></script>
</head>

<body ng-app="clientApp">
  <div ng-controller="TestCtrl">
    <input type="text" ng-model="name">
    <button ng-click="save()" > save</button>
    
  </div>
  
  <div ng-init="getnames()" ng-controller="TestCtrl2">
     <div  ng-repeat="name in names">
       {{name}}
       </div>
     
  </div>
</body>

</html>
&#13;
&#13;
&#13;

DEMO WITH ROUTE

答案 1 :(得分:0)

I think you are switching controller due to state change. Then an easy way to pass data from parent controller to any child controller apart from using factory or services is using state params

// In parent controller
$state.go('child.state', {
        'key' : $scope.value
    });
 //In child controller
$scope.sentObject = angular.copy($stateParams.key);