简体   繁体   中英

Two way binding with AngularJS select for a child object

I have an angular form with this select element:

<select ng-model="expense.category" ng-options="category.code for category in categories"></select>

where expense is my object to create/edit in the form and expense.category points to child object category (with properties "id" and "code"), which is to be selected by this control.

This all works perfect for creating new expenses - category gets saved just the way it should be. When loading an expense for editing everything is fine also - the expense has its category in the controller. But on the form the select does not get pre-filled with the correct category-entry, it is empty, although all the categories are loaded into the select element. So binding works only one way (from form to model) but not in the other way (from model to form) for the select field. All the other fields (properties of expense) get filled correctly into the edit form though.

Any ideas how to solve this?

Comparison between ng-options and ng-model is done by reference, not value. I suspect your expense.category , when loaded, is a separate entity from the ones in the categories array. You should probably populate your expense.category with a category from categories . Another option would be to replace the select with a dropdown. This would represent a bit more code (you would have to handle the binding yourself on the ng-click) but would give you more control on comparison and display.

The expense.category model must be an existing item in the categories array.

What you can do to make this happen is to search for the right item in the array (with the help of the code property) and replace your existing copy of the category with the reference in the categories array .

This could be done like this:

myApp.controller('ctrl', function($scope) {
    $scope.categories = [{code: 'sport'}, {code: 'music'}, {code: 'culture'}];
    $scope.expense = {category: {code: 'sport'}};

    function replaceWithReference(expense) {
        var code = expense.category.code;
        for(var i=0; i < $scope.categories.length; i++) {
            if($scope.categories[i].code === code) {
                expense.category = $scope.categories[i];
                return;
            }
        }
    }

    replaceWithReference($scope.expense);
});

Here is the working jsfiddle-demo

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