Hello Guys我想发送$ scope.test数据,以便在我的其他控制器“FormCtrl”中使用它 而$ scope.content是一个id和许多其他对象,在$ scope.test中也是一个id,我想在同一个id上使用这两个数据......但更重要的是让scope.test数据使用它在FormCtrl ... greez
var app = angular.module('surveyApp', []);
app.controller('BackendCtrl', function($scope, $http){
var apiURL = "JSON DATA";
var apiURL2 = "DIFFERENT JSON DATA";
$http.get(apiURL).then(function(response) {
$scope.content = response.data;
});
$http.get(apiURL2).then(function(response) {
$scope.test = response.data;
});
});
app.controller('FormCtrl', function($scope, $http) {
$scope.formData = {};
$scope.formData.id = $scope.a.id;
$scope.formData.checkbox = "1";
$scope.formData.textarea = $scope.a.id;
$scope.save = function(formData) {
$scope.submitFormData = angular.copy(formData);
$http({
method: 'POST',
url: 'update.php',
data: $scope.submitFormData,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
};
});
答案 0 :(得分:0)
这取决于您的层次结构的构建方式。假设您要在FormCtrl中使用BackendCtrl中的数据。如果您的FormCtrl位于BackendCtrl内部,如下所示:
<div ng-controller="BackendCtrl">
...
<div ng-controller="FormCtrl"></div>
...
</div>
然后FormCtrl继承了它的所有变量。您可以像在FormCtrl中的范围一样调用它们,因为它们实际上是:
var app = angular.module('surveyApp', []);
app.controller('BackendCtrl', function($scope, $http){
$scope.myVariable = "foo";
});
app.controller('FormCtrl', function($scope, $http) {
console.log($scope.myVariable); // logs "foo"
});
<小时/> 如果您的控制器是兄弟姐妹,请执行以下操作:
<div ng-controller="BackendCtrl"></div>
...
<div ng-controller="FormCtrl"></div>
唯一清洁的选择是注入$rootScope
并将所需的变量广播到所有子范围。
var app = angular.module('surveyApp', []);
app.controller('BackendCtrl', function($scope, $http, $rootScope){
$scope.myVariable = "foo";
$rootScope.$broadcast('broadcastEvent', $scope.myVariable);
});
app.controller('FormCtrl', function($scope, $http) {
$scope.$on('broadcastEvent', function(event, broadcastedVariable) {
// optional: $scope.myVariable = "foo";
console.log(broadcastedVariable); // logs "foo"
});
});
如果您的FormCtrl是BackendCtrl的父级,如下所示:
<div ng-controller="FormCtrl">
...
<div ng-controller="BackendCtrl"></div>
...
</div>
然后你必须从BackendCtrl发出数据然后在FormCtrl中使用它:
var app = angular.module('surveyApp', []);
app.controller('BackendCtrl', function($scope, $http, $rootScope){
$scope.myVariable = "foo";
$scope.$emit('broadcastEvent', $scope.myVariable);
});
app.controller('FormCtrl', function($scope, $http) {
$scope.$on('broadcastEvent', function(event, broadcastedVariable) {
// optional: $scope.myVariable = "foo";
console.log(broadcastedVariable); // logs "foo"
});
});
但是不建议使用最后两个选项,因为这会忽略整个范围和控制器的问题。如果你想从另一个不是它的父控制器的控制器访问控制器中的数据,那么最好的方法就是将它作为父级,或者当然在新创建的父级控制器中定义数据。