Giorgio Piatti Giorgio Piatti - 5 months ago 26
AngularJS Question

Unable to get property 'subject' of undefined or null reference

I'm trying to make a little app in ionic, but it gave me that error when i call the

$scope.saveClass()
function from the UI.

Unable to get property 'subject' of undefined or null reference

I don't understand because he doesn't work. Premise: i'm new to ionic/angularjs developing.

I thank you in advance for helping

code (www/js/controllers.js)

angular.module('starter.controllers')
.service("DB", function() {
this.classDB = new PouchDB("classesDB");
})

.controller("AddClassCtrl", function ($scope, DB) {
$scope.saveClass = function () {
var newclass = {
"_id": $scope.class.subject,
"subject": $scope.class.subject,
"room": $scope.class.room
}

DB.classDB.put(newclass);

window.location.href = '#app/schedule'
};
})


Code (add-class.html)

<ion-content controller="AddClassCrtl">
<div class="list">

<!--Select the subject-->
<label class="item item-input item-select">
<div class="input-label">
Subject
</div>
<button class="button button-block button-positive overflowShow"> Add a subjects </button>
<select class="item-input" ng-model="class.subject" ng-selected="class.subject">
<option ng-repeat="subject in subjects">{{subject}}</option>
</select>
</label>
<!--Insert the room number-->
<label class="item item-input item-stacked-label">
<input type="text" placeholder="Room" ng-model="class.room" ng-text-change="class.room">
</label>
<div class="item">
<button ng-click="discardClass()" class="button button-block">Discard</button>
<button ng-click="saveClass()" class="button button-block">Save</button>
</div>
</div>
</ion-content>

Answer

It's probably because you didn't initialize $scope.class variable and in fact, when you try to access $scope.class.subject, $scope.class is undefined. Add this code at the beginning of your controller:

$scope.class = {};