【发布时间】:2015-09-23 22:32:01
【问题描述】:
我不知道如何从嵌套(子)控制器访问数据。
<form ng-controller="TestController as test" ng-submit="submit()">
<h5>Employee name :</h5>
<div ng-controller="mainCtrl" class="row-fluid">
<form class="row-fluid">
<div class="container-fluid">
<input type="text" ng-model="name" typeahead="name for name in names | filter:$viewValue" />
</div>
</form>
</div>
<h5>Comment : </h5>
<textarea ng-model="test.test_content"></textarea>
<input type="submit" id="submit" value="Submit" />
</form>
如您所见,我有 2 个控制器。主要的是一个表单,第二个是一个输入框,允许用户使用预先输入的方式在列表中搜索名称。
我希望能够在我的 TestController 的子控制器 (mainctrl) 中访问 ng-model="name" 的内容。
我尝试使用 $scope.name 直接访问它,但它不起作用。 我也尝试将 test.name 作为 ng-model,但它也不起作用。
我正在将我的 TestController 的数据发送到我的服务器,并希望直接从 TestController 发送来自我的 mainCtrl 的数据(名称)。这样当我的用户单击提交时,它会在 $http.post 请求中同时发送名称和 test_content。
有人知道怎么做吗?
谢谢
我找到了这个,但它并没有真正帮助.. https://fdietz.github.io/recipes-with-angular-js/controllers/sharing-models-between-nested-controllers.html
编辑:
我的搜索控制器
.controller("mainCtrl", function ($scope, $http) {
$scope.selected = '';
$http.get('/feedbacks/search.json').
then(function(response) {
$scope.succes = " ok "
$scope.names = response.data;
// this callback will be called asynchronously
// when the response is available
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
$scope.succes = " error"
});
});
我的表单控制器:
angular.module('FeedbackTool')
.controller('TestController',['$scope', '$http', function($scope,$http) {
$http.get('/feedbacks.json').
then(function(response) {
$scope.succes = " ok "
$scope.list = response.data;
// this callback will be called asynchronously
// when the response is available
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
$scope.succes = " error"
});
$scope.submit = function() {
$http.post('/feedbacks.json', { data:this.test }).
then(function(response) {
$scope.succes = 'sent';
// this callback will be called asynchronously
// when the response is available
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
$scope.succes = 'fail';
});
};
}]);
【问题讨论】:
-
您也可以发布您的控制器代码吗?
标签: angularjs