1

HTML:

...
<input ng-init="item.check=false" type="checkbox" ng-model="item.check">
...
<input ng-init="item.name=''" class="form-control" ng-model="item.name">
...

JS:

var myApp = angular.module('myApp', []);
myApp.controller('AppCtrl', function ($scope, $http) {
var refresh = function() {
    $scope.item.check = false;
    $scope.item.name = "";

}
//Call upon loading app to initialize values, also called upon events to refresh the field
refresh();

I initially thought that just the JS is sufficient to initialize the values and so I got rid of both the checkbox and the form's ng-init then ended up getting the error:

TypeError: Cannot set property 'name' of undefined

The app works if I just leave both ng-init. It also works when I remove the ng-init from only one of the 2 elements (so either from the checkbox or the form) but it will not work if I remove both. What is going on here? Am I doing this correctly or is there a better way to initialize?

Thanks.

2 Answers 2

1

You can add $scope.item = {} in first line of your controller.

Javascript reports error when you are trying to access $scope.item.name when $scope.item itself doesn't exist (or not an object in some cases).

When you do ng-init, angular creates the object for you so you don't get the error.

Sign up to request clarification or add additional context in comments.

2 Comments

I see! Is it correct to say that we are initializing item as an object or a dictionary?
Object. javascript doesn't have a dictionary type AFAIK, we just use object to implement one.
1

Add this to the controller

$scope.item = {};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.