How to set first controller data another controller

谁说我不能喝 提交于 2019-12-10 11:55:09

问题


Here I added categoryCtrl and ProductCtrl. This code line console.log(category); is working properly. How to bind this data for the product controller using for loop or whatever.

.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)  {

});

回答1:


you can pass Datas either Rootscope or Factories or services

JS using factory

<!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>



回答2:


i fix your code, using a service should be a correct solution.

.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;
   }

});



回答3:


 $scope.selectedJsonObject=function(category){
    console.log(category);
$scope.$emit('eventName', { message: category});
} 

and in your productctrl use

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


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


来源:https://stackoverflow.com/questions/38563874/how-to-set-first-controller-data-another-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!