在AngularJS中,我有一个表单,在提交时,将数据传递给控制器并将其发送到API。
形式:
<form ng-submit="newCompany()">
<div class="form-group" ng-controller="CompaniesController">
<label>ID</label><input type="text" name="id" id="id" ng-model="newCompany.id" tabindex="1" class="form-control">
<label>Name</label><input type="text" name="name" id="name" tabindex="2" ng-model="newCompany.name" class="form-control">
<label>Primary Contact</label><input type="text" name="primary_contact" id="primary_contact" tabindex="2" ng-model="newCompany.primary_contact" class="form-control">
<label>Address</label><input type="text" name="address" id="address" tabindex="2" ng-model="newCompany.address" class="form-control">
<label>Function</label><input type="text" name="function" id="function" tabindex="2" ng-model="newCompany.function" class="form-control">
<label>Telephone</label><input type="text" name="telephone" id="telephone" tabindex="2" ng-model="newCompany.phone" class="form-control">
<label>Fax</label><input type="text" name="fax" id="fax" tabindex="2" ng-model="newCompany.fax" class="form-control">
<label>URL</label></label><input type="text" name="url" id="url" tabindex="2" ng-model="newCompany.url" class="form-control">
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<input type="submit" name="add-submit" id="add-submit" tabindex="10" class="form-control btn btn-primary" value="Add Company">
<br>
<div class="text-center">
<p ng-show="addCompany"><span class="label label-info">{{ addCompany }}</span></p>
</div>
</div>
</div>
</div>
</form>
控制器......
app.controller("CompaniesController", ['$scope', 'Companies', function($scope, Companies) {
$scope.title = 'Companies';
$scope.title_sub = 'Add Company';
$scope.companyData = {
id: $scope.newCompany.id,
name: $scope.newCompany.name,
primary_contact: $scope.newCompany.primary_contact,
address: $scope.newCompany.address,
function: $scope.newCompany.function,
telephone: $scope.newCompany.phone,
fax: $scope.newCompany.fax,
url: $scope.newCompany.url
};
$scope.newCompany = function() {
var company = new Companies($scope.companyData);
company.$save();
};
$scope.companies = Companies.query();
}]);
然而 - 我收到一条错误,上面写着“无法读取未定义的属性'id'”
有人知道这里有什么问题吗?我认为$ scope。[NG-MODEL]获取表格数据......
答案 0 :(得分:1)
你有一个$ scope.newCompany变量,它是一个函数,而不是一个对象。
初始化$ scope.companyData时,调用id:$ scope.newCompany.id,其中$ scope.newCompany未定义。尝试首先使用其所有属性进行定义($ scope.newCompany = { id:&#34;&#34;, ... })
将您的提交功能称为其他内容。
不要创建名称本身为&#39;功能的函数&#39;。 (function:$ scope.newCompany.function)。这是作为关键字保留的。
如果没有回复,这些步骤可能会接近您想要查看的结果。