如何设置第一个控制器数据另一个控制器
How to set first controller data another controller
在这里我添加了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);});
});
相关文章:
- 而循环只设置php中输入字段中的第一个值
- 从我的控制器返回一个不同于200的代码以触发ajax错误,这被认为是一种好的做法吗
- 错误:$injector:modulerr模块错误(我的第一个SPA应用程序)
- IE11中的第二个调用取消了第一个Fetch API调用
- Javascript XMLHttpRequest——只有第一个POST请求有效
- 使用javascript或angularjs特定过滤器搜索字符串中第一个img标记的json值
- 将OnClick函数设置为<ul>,最后一个ul是擦除第一个ul-s
- RxJS油门行为;立即获取第一个值
- angularjs调用事件中控制器的一个函数
- Angular UI网格:如何通过第一个UI网格中的按钮使第二个UI网格可见
- 选择多个实例中的第一个
- 如何在调用下一个请求之前完成第一个Ajax Get请求
- Lodash:返回对象的第一个键,该对象的值(即数组)中有一个给定的元素(即字符串)
- 看起来第一个console.log是'It’不太对
- 与杜兰达尔合作的第一个JavaScript项目.尝试从第三方 API 获取数据
- 节点发布错误对象的第一个“属性”
- Javascript:表单验证getElementById仅返回第一个id元素
- 仅将 CSS 规则应用于
中的第一个 ,而不分配类/ID - JS在隐藏未定义的值后仅从数组中返回第一个id的值
- 获取行中的第一个值“;点击“;并传递给控制器