我举一个小例子来提交一个包含用户名和电子邮件的表单。
我想为输入设置一个默认值,如下所示:
let app = angular.module('myApp', []);
app.controller('myController', function ($scope) {
let account = {};
// TypeError: Cannot set property 'name' of undefined
$scope.account.name = 'Hermione';
// TypeError: Cannot set property 'email' of undefined
$scope.account.email = 'hermione@gmail.com';
$scope.form_submit = function ($event, account) {
$event.preventDefault();
console.log('name', account['name']);
console.log('email', account['email']);
};
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form ng-app="myApp" ng-controller="myController">
<div>
<label>Name:</label>
<input type="text" ng-model="account.name" />
</div>
<div>
<label>Email:</label>
<input type="email" ng-model="account.email" />
</div>
<div>
<a href="javascript:;" ng-click="form_submit($event, account)">Submit</a>
</div>
</form>
&#13;
错误讯息:
TypeError:无法设置属性&#39; name&#39;未定义的
或
TypeError:无法设置属性&#39; email&#39;未定义的
我的第一个问题:我该如何解决?
我也尝试过:用ng-model="account.name"
替换ng-model="name"
。然后,$scope.name = 'Hermione'
。它工作正常。抱歉,我不想这样使用。
第二种情况:我想通过ViewData
设置默认值。我试过了:
@{
// I've set a breakpoint to check value before, ViewData["Name"] is not null
string name = ViewData["Name"]?.ToString() ?? string.empty;
}
然后:
<input type="text" ng-model="account.name" value="@name" />
该输入始终为空白。
所以,我的第二个问题是:出了什么问题?
p / s:我已提到问题:Cannot set property 'x' of undefined in AngularJs [duplicate]。但它似乎不是我的问题。我无法在那里找到答案。
答案 0 :(得分:2)
在您的控制器代码中,在$ scope下定义新对象account
,如下所示:
....
// change let account = {}; to the following:
$scope.account = {};
// now you could set $scope.acount.name
$scope.account.name = 'Hermione';
...
答案 1 :(得分:1)
let app = angular.module('myApp', []);
app.controller('myController', function ($scope) {
var account = {};
// TypeError: Cannot set property 'name' of undefined
account.name = 'Hermione';
// TypeError: Cannot set property 'email' of undefined
account.email = 'hermione@gmail.com';
$scope.account=account;
$scope.form_submit = function ($event, account) {
$event.preventDefault();
console.log('name', account['name']);
console.log('email', account['email']);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form ng-app="myApp" ng-controller="myController">
<div>
<label>Name:</label>
<input type="text" ng-model="account.name" />
</div>
<div>
<label>Email:</label>
<input type="email" ng-model="account.email" />
</div>
<div>
<a href="javascript:;" ng-click="form_submit($event, account)">Submit</a>
</div>
</form>