Tân Nguyễn Tân Nguyễn - 1 year ago 66
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) {

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">
<input type="text" ng-model="account.name" />

<input type="email" ng-model="account.email" />

<a href="javascript:;" ng-click="form_submit($event, account)">Submit</a>

Error message:

TypeError: Cannot set property 'name' of undefined


TypeError: Cannot set property 'email' of undefined

My first question: how can I fix it?

I also tried: replacing
. 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
. I've tried:

// 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" />

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 Source

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'; 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download