昨天我询问了控制器之间的数据交换形式。但正确的问题是我如何在重定向某个视图之后在控制器之间交换数据。这是一个想法(pseudoCode):
controller1("$scope", function($scope){
var val1 = $scope.dataFromview
href = ("#/search", val1);
});
controller2("$scope", function($scope, controller1){
var val2 = controller1.val1;
//make something with val2
});
由于
答案 0 :(得分:2)
查看http://egghead.io/lessons/angularjs-sharing-data-between-controllers
还有关于stackoverflow的事先发布 Passing data between controllers in Angular JS?
您可以定义将注入两个控制器的服务:
app.service('exampleService', function() {
var val1;
var href = "#/search";
var setVal = function(newString) {
val1 = newString
};
var getVal = function(){
return val1;
};
return {
setVal: setVal,
getVal: getVal
};
});
依赖关系将服务注入两个控制器。
在First控制器中,定义一些设置值的操作:
app.controller('ControllerOne', function($scope, exampleService) {
$scope.addValOne = function(newString){
exampleService.setVal(newString);
};
});
在第二个控制器中,从服务中获取val1:
app.controller('ControllerTwo', function($scope, exampleService) {
$scope.val1 = exampleService.getVal();
});
答案 1 :(得分:0)
假设我们想要在控制器之间共享Product对象。在这里,我创建了一个名为SharedDataService的AngularJS服务,如下面的代码段所示:
myApp.service('SharedDataService', function () {
var Product = {
name: '',
price: ''
};
return Product;
});
接下来让我们继续使用SharedDataService创建两个不同的控制器。在控制器中,我们使用上一步中创建的服务。可以如下所示创建控制器:
var myApp = angular.module("myApp", ['CalService']);
myApp.controller("DataController1", ['$scope', 'SharedDataService',
function ($scope, SharedDataService) {
$scope.Product = SharedDataService;
}]);
myApp.controller("DataController2", ['$scope', 'SharedDataService',
function ($scope, SharedDataService) {
$scope.Product = SharedDataService;
}]);
在视图中我们可以简单地使用控制器,如下面的清单所示:
<h2>In Controller 1h2>
<input type="text" ng-model="Product.name" /> <br/>
<input type="text" ng-model="Product.price" />
<h3>Product {{Product.name}} costs {{Product.price}} h3>
div>
<hr/>
<div ng-controller="DataController2">
<h2>In Controller 2h2>
<h3>Product {{Product.name}} costs {{Product.price}} h3>
div>