AngularJS问题:ng-options无法从JavaScript数组获取数据
Let’s work through why your dropdown isn’t populating with the departments array data and get it sorted out step by step.
Common Issues & Solutions
Missing ng-controller Binding
The code you shared doesn’t show where you’ve attached theefControllerto your view. Without this connection, AngularJS can’t link your$scope.departmentsarray to the template. Make sure your form (or a parent container) includes theng-controllerdirective:<div ng-controller="efController"> <!-- Your existing form content here --> <div class="form-group"> <label for="department" class="col-sm-3 control-label">Department</label> <div class="col-sm-9"> <select name="department" id="department" class="form-control" ng-model="employee.department" ng-options="dept for dept in departments"> </select> </div> </div> </div>Verify Scope Variable Availability
Double-check that your$scope.departmentsarray is initializing correctly. Add a quick console log in your controller to confirm it exists:angularFormsApp.controller('efController', function efController($scope, efService) { $scope.employee = efService.employee; $scope.departments = [ "Engineering", "Marketing", "Finance", "Administration" ]; // Debug log to confirm the array loads console.log("Departments list:", $scope.departments); });Open your browser’s developer tools (F12) and check the console—if you don’t see the array printed, there might be an issue with your module setup or controller injection.
Initialize ng-model Properly
Ifemployee.departmentdoesn’t have an initial value that matches an item indepartments, the dropdown might look empty even though options exist. Set a default value to fix this:angularFormsApp.controller('efController', function efController($scope, efService) { $scope.employee = efService.employee; $scope.departments = [ "Engineering", "Marketing", "Finance", "Administration" ]; // Set initial selection to the first department $scope.employee.department = $scope.departments[0]; });
Full Working Example
Here’s the complete code with all fixes applied:
HTML
<div ng-controller="efController"> <div class="form-group"> <label for="department" class="col-sm-3 control-label">Department</label> <div class="col-sm-9"> <select name="department" id="department" class="form-control" ng-model="employee.department" ng-options="dept for dept in departments"> </select> </div> </div> </div>
JavaScript
angularFormsApp.controller('efController', function efController($scope, efService) { $scope.employee = efService.employee || {}; // Ensure employee object exists $scope.departments = [ "Engineering", "Marketing", "Finance", "Administration" ]; $scope.employee.department = $scope.departments[0]; // Set default selection });
If you’re still stuck, check your browser console for AngularJS error messages—they’ll almost always point you directly to the root issue (like a typo in the controller name or missing module dependency).
内容的提问来源于stack exchange,提问作者Alden Linn

