2016-07-25 88 views
0

这里我添加了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) { 

}); 
+1

创建一个'服务',它将负责在角度组件之间共享数据。 –

回答

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

,并在您productctrl 使用

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


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

通过您的应用程序实现此目的,创建服务更加干净,可测试且可重复使用的解决方案,然后是传播事件。 –

+0

也许你是对的,但它是更有效和简单的方法,此外,$和$广播也是可测试的。 –

+0

在哪里添加这些代码我的朋友...? – moni123

1

你可以通过使用工厂

<!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> 
DATAS要么Rootscope工厂或服务

JS

+0

如何在我的项目中添加这些示例我的朋友 – moni123

0

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

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

}); 
+0

此代码现在正常工作我的朋友... – moni123

+0

'无法找到变量:$ http'会在控制台中显示此错误我的朋友 – moni123

+0

我必须添加这个服务文件单独或在同一个控制器我的朋友 – moni123

相关问题