如何设置第一个控制器数据另一个控制器

How to set first controller data another controller

本文关键字:控制器 第一个 数据 另一个 设置 何设置      更新时间:2023-09-26

在这里我添加了categoryCtrl和ProductCtrl。此代码行console.log(category);工作正常。如何使用for循环或其他方法为产品控制器绑定这些数据

.controller('CategoryCtrl', function($scope, $http) {
    var vm = this;
    vm.playlists = {};
    $http.get("http://localhost/youtubewebservice/shop-categorylist-product.php").then(function(response) {
      vm.playlists = response.data.category;
      console.log(response.data.category);
    });

    $scope.selectedJsonObject=function(category){
        console.log(category);
    } 
})
.controller('productCtrl', function($scope, $stateParams)  {
});

您可以通过Rootscope或Factory或服务传递数据

JS使用工厂

<!doctype html>
<html ng-app="project">
<head>
    <title>Angular: Service example</title>
    <script src="https://code.angularjs.org/angular-1.0.1.js"></script>
    <script>
var projectModule = angular.module('project',[]);
projectModule.factory('theService', function() {  
  var data ={}
  data.x ={}
    return data;
});
function FirstCtrl($scope, theService) {
  console.log(theService)
    $scope.name = "First Controller datas";
    theService.x =  $scope.name ;
}
function SecondCtrl($scope, theService) {   
    $scope.someThing = theService.x; 
}
    </script>
</head>
<body>  
    <div ng-controller="FirstCtrl">
        <h2>{{name}}</h2>
    </div>
    <div ng-controller="SecondCtrl">
        <h2> Second Controller recives {{someThing}}</h2>
    </div>
</body>
</html>

我修复了您的代码,使用服务应该是一个正确的解决方案。

.controller('CategoryCtrl', function($scope, myService) {
    var vm = this;
    vm.playlists = myService.playList;    
    $scope.selectedJsonObject=function(category){
        console.log(category);
    } 
})
.controller('productCtrl', function($scope, $stateParams, myService)  {
  this.playlists = myService.playList;
});
.service('myService', function($http){
    var playlist = {};
    $http.get("http://localhost/youtubewebservice/shop-categorylist-product.php").then(function(response) {
      playlist = response.data.category;
      console.log(response.data.category);
    });
   this.playList = function(){
     return playList;
   }
});
 $scope.selectedJsonObject=function(category){
    console.log(category);
$scope.$emit('eventName', { message: category});
} 

以及在您的产品中使用

.controller('productCtrl', function($scope, $stateParams)  {
 $scope.$on('eventName', function (event, args) {

$scope.message = args.message;
 console.log($scope.message);});
});