我从表单中推送输入有一些问题
下面有一些检测到错误的代码行 我也在CodePen
上重新创建了它$scope.dish.comments.push(Object.keys{rating: $scope.comment.rating, comment: $scope.comment.comment, author: $scope.comment.author, date: $scope.comment.date});
因此,每次我提交表单时,我总会在控制台中收到这样的通知
TypeError:无法读取undefined
的属性'comments'
我已经在另一个控制器中声明了$scope.dish = dish;
,所以我希望我可以从另一个控制器访问它,但它没有按照我希望的方式工作
答案 0 :(得分:1)
您正在尝试在两个控制器之间共享数据,我建议您使用服务工厂进行DishDetails,然后在两个控制器上注入依赖关系,然后修改数据,将反映到每个控制器。
以下是使用工厂服务共享数据的方法。
function factory() {
var service = {
set: setData,
get: getData
};
service.records = [{
FirstName: 'FirstName',
LastName: 'LastName',
Age: '21'
}];
return service;
function getData() {
return service.records;
}
function setData(data) {
service.records.push(data);
}
}
angular
.module('mainApp', [])
.factory('dataRecords', factory)
.controller('AddDataController', function($scope, dataRecords) {
$scope.AddRecord = function() {
var data = {
FirstName: $scope.FirstName,
LastName: $scope.LastName,
Age: $scope.Age
}
dataRecords.set(data)
}
})
.controller('ViewDataController', function($scope, dataRecords) {
$scope.records = dataRecords.get();
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link data-require="bootstrap-css" data-semver="3.3.6" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" />
<div ng-app="mainApp">
<div ng-controller="AddDataController">
First Name:
<input type="text" ng-model="FirstName" name="FirstName" placeholder="Enter First Name" required>Last Name:
<input type="text" ng-model="LastName" placeholder="Enter Last Name">Age:
<input type="number" ng-model="Age">
<button type="button" ng-click="AddRecord()">ADD</botton>
</div>
<div ng-controller="ViewDataController" class="container">
<h3>Record List Controller</h3>
<table class="table">
<tr>
<th>FirstName</th>
<th>LastName</th>
<th>Age</th>
</tr>
<tr ng-repeat="person in records">
<td>{{ person.FirstName }}</td>
<td>{{ person.LastName }}</td>
<td>{{ person.Age }}</td>
</tr>
</table>
</div>
</div>
答案 1 :(得分:0)
添加你的ng-controller =&#34; DishDetailController&#34;到父行内容div,以便其他控制器将继承$ scope.dish。因此:
<div class="row row-content" ng-controller="DishDetailController">
<div class="col-xs-9 col-xs-offset-1" >
...
</div>
<div class="col-xs-9 col-xs-offset-1" ng-controller="DishCommentController">
...
</div>
</div>