Tân Nguyễn Tân Nguyễn - 25 days ago 7
AngularJS Question

Cannot set property 'name' of undefined from $scope.account.name

I'm making a small example to submit a form with user name and email.

I want to set a default value to the input, like this:



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>





Error message:


TypeError: Cannot set property 'name' of undefined


or


TypeError: Cannot set property 'email' of undefined


My first question: how can I fix it?

I also tried: replacing
ng-model="account.name"
with
ng-model="name"
. Then,
$scope.name = 'Hermione'
. It works fine. Sorry but I don't want to use this way.

The second case: I want to set default value via using
ViewData
. I've tried:

@{
// I've set a breakpoint to check value before, ViewData["Name"] is not null
string name = ViewData["Name"]?.ToString() ?? string.empty;
}


Then:

<input type="text" ng-model="account.name" value="@name" />


That input is always blank.

So, my second question is: what's wrong?

p/s: I've refered question: Cannot set property 'x' of undefined in AngularJs [duplicate]. But it doesn't seem like my question. I can't find the answer there.

Answer

In your controller code, define the new object account under $scope as follows:

  ....
  // change let account = {}; to the following:
  $scope.account = {};

  // now you could set $scope.acount.name
  $scope.account.name = 'Hermione'; 
  ...