当ng-options被过滤时,angular.js将模型设置为null

时间:2015-10-27 14:51:26

标签: angularjs angularjs-filter

我有一个course categorycourse列表选择输入。根据选定的课程,我想过滤ng-options,以便用户不会选择两次相同的课程

  <td>
    <select ng-show="course._courseId" class="form-control" 
            ng-model="course.lookup_course_id" 
            ng-options="s.id as s.name for s in subcourses[course._courseId] | filter:notSelectedCourse">
      <option value="">Select Course</option>
    </select>
  </td>

我正在使用以下功能过滤所选课程

$scope.notSelectedCourse = function(scourse) {
    if (!$scope.course_list)
      return true;

    for (var d, i = 0; i < $scope.course_list.length; i++) {
      d = $scope.course_list[i];
      if (d.lookup_course_id == scourse.id)
        return false;
    }

    return true;
};

但是,angular.js不会更新第二个选择框值并更新模型。

当我禁用过滤器时,它工作正常,但我需要添加过滤器,以便用户不能选择相同的过程两次。

这是DEMO,尝试使用选择输入

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

希望这是你所期待的...... 也确实对类别选择设置了相同的约束 demo http://embed.plnkr.co/tkr4nWedY45eGn48aFtP/

// This filter/predicate will invoked when select renders the options for each item in categories  ...
// If all course of the categerory has been selected
// then the options can be displayed. Else the option can be displayed to selected ....
$scope._filters.selectableCategories = function(selectedCategoryId) {
    return function(item) {         
        // 1. get the selected courses whose :
            // 1.1 course id is set/ NOT NULL... hence we ignore the courses that the user has not yet selected the course ...
            // 1.2 categerory == item
            // 1.3 categerory is not the current select category ... bcos the current selected category IS ALWAYS SELECTABLE ...    
        //2. If the above count  NOT EQUAL the course in category, then is selectable ...
        return $scope._courseList
            .filter(function(elm) { return elm._courseId && elm._categoryId !== selectedCategoryId && elm._categoryId === item.id;})
            .length != $scope._courses[item.id].length;
    }
}

// This filter/predicate will invoked when select renders the options for each item in courses_of_category  ...
// If the option has is not in the selected courses 
// then the options can be displayed. Else the option can be displayed to selected ....
$scope._filters.selectableCourses = function(selectedCategoryId, selectedCourseId) {
    return function(item) {
        // 1. get all the select courses :
            // 1.1 category === selected categerory
            // 1.2 course is not the selected course ... again bcos the current selected course IS ALWAYS SELECTABLE ...
        // 2. get the array of courseIds ...
        // 3. If item's id IS NOT IN the array, then item IS SELECTABLE ...
        return $scope._courseList
            .filter(function(elm) {return elm._categoryId == selectedCategoryId && elm._courseId !== selectedCourseId;})
            .map(function(elm){ return elm._courseId; })
            .indexOf(item.id) < 0;
    }
}