简体   繁体   中英

Having trouble displaying and saving with ng-options

My original error was that my select options weren't populating, I figured out that it was because angular couldn't see my scope because it was inside my "create" function. When I moved the scope object out of that function it populated my options, but when I selected an option they disappeared.... This was because my select was tied into an ng-model that didnt have access to that scope. If I change the model, when I save it to the database it saves it as [object Object],[object Object],[object Object] Which is not what I want.

I am confused because, doesn't my select need to be tied to the correct model in order to save to the right attribute in the database? How does a model see a scope when you aren't supposed to manipulate date in the model?

Any help would be greatly appreciated

MODEL

 var StrainSchema = new Schema({ name: { type: String, default: '', required: 'Please specify a Strain name', trim: true }, description: { type: String, default: '', required: 'Describe the Strain', trim: true }, stype: { type: String, default: '', required: 'Specify type of Strain', trim: true }, created: { type: Date, default: Date.now }, user: { type: Schema.ObjectId, ref: 'User' } }); 

CONTROLLER

 $scope.stype = [ {id: '1', name: 'Indica'}, {id: '2', name: 'Sativa'}, {id: '3', name: 'Hybrid'} ]; // Create new Strain $scope.create = function() { // Create new Strain object var strain = new Strains ({ name: this.name, description: this.description, stype: this.stype }); // Redirect after save strain.$save(function(response) { $location.path('strains/' + response._id); // Clear form fields $scope.name = ''; $scope.description = ''; $scope.stype = ''; }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; 

HTML / VIEW

  <label class="control-label" for="stype">Type</label> <div class="controls"> <select name="stype" id="stype" class="form-control" data-ng-model="stype" data-ng-options="type.name for type in stype"> <option value="">-- Choose Type --</option> </select> </div> 

The problem was that I wasnt specifying the correct string for the value attribute.

 data-ng-options="type.name as type.name for type in stypes" 

The first type.name puts my "name" string into the value attribute, the value is what is being saved to the database, not the text in the option.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM