javascript - 如何设置第一个 Controller 数据另一个 Controller

标签 javascript jquery angularjs angularjs-scope

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

.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 或工厂或服务

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>

关于javascript - 如何设置第一个 Controller 数据另一个 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38563874/

相关文章:

angularjs - 带有选项卡和表格的 Angular 性能

javascript - 从 Callback hell 转换为 Promise

javascript - 禁用 "Changes you made may not be saved"弹窗

javascript - AJAX 响应后重新加载 amchart

angularjs - 无法让 ng-animate 移除 ng-hide

html - $范围未定义

javascript - 世界上最简单的 JavaScript 都行不通!

javascript - Webdriver.waitUntil 未按预期工作

javascript - jQuery:是否可以将字段/方法附加到 jQuery 包装器对象?

javascript - jQuery使图像旋转间隔平滑减小