javascriptangularjsangularjs-directiveangularjs-scopeangular-chosen

Cannot create property 'subjects' on number '1' using AngularJs


I want to select multiple subjects across one course but can't do so

I have two dropdown lists one for course selection and one for subjects selection. For multiple selection of the subjects I use the angular-chosen plugin, I can select multiple subjects only in the case when the Course is not selected from the dropdown list. But when I select the Course from the dropdown list then I can't select even one subject from the dropdown list

Following is my AddCourseController.js and related HTML

(function() {

  var myApp = angular.module("myApp");

  var AddCourseController = function($scope, CourseService, TeacherService) {

    var onCourses = function(courses) {
      $scope.courses = courses;
    }
    var onError = function(response) {
      $scope.error = true;
      $scope.errors = response.data;
    };
    CourseService.courses().then(onCourses, onError);
    TeacherService.getSubjects().then(function(data) {
      $scope.subjects = data
    });
  };

  myApp.controller("AddCourseController", AddCourseController);
}());
<div class="form-group">
  <label>Select Course</label>
  <select ng-model="course" class="form-control"
          ng-options="course.IdCourse as course.Name for course in courses track by course.IdCourse">
  </select>
</div>
<div class="form-group" ng-class="{ 'has-error' : 
   addCourseForm.subjects.$invalid && !addCourseForm.subjects.$pristine }">
  <label class="pull-left">Select Subjects</label>
  <a class="pull-right btn btn-primary btn-xs" data-toggle="modal" data- target="#add-subject">Add Subject</a>
  <select chosen multiple class="form-control" 
          ng-model="course.subjects"
          ng-options="subject.IdSubject as subject.Name for subject in subjects">
  </select>
  <p ng-show="addCourseForm.subjects.$invalid && 
  !addCourseForm.subjects.$pristine" class="help-block">Subject is required.
  </p>
</div>

Solution

  • Change the course selector to return the entire course object to the ng-model:

    <div class="form-group">
      <label>Select Course</label>
      <select ng-model="course" class="form-control"
              ng-options="course ̶.̶I̶d̶C̶o̶u̶r̶s̶e̶ as course.Name for course in courses track by course.IdCourse">
      </select>
    </div>