Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I associate objects as models using ng-options in angularjs

Tags:

angularjs

Assume I have two objects: color and shirt.

Each shirt can have multiple properties as well as multiple colors which is basically an array of color objects.

function MyCntrl($scope) {
    $scope.colors = [
        {
            label:"Red",
            value:"r-e-d",
            available:true
        },
        {
            label:"Blue",
            value:"b-l-u-e",
            available:false
        }   
    ];

    $scope.shirts=[{
        size:"M",
        cost:100,
        colors:[ ]
    }
    ]
}

How can I use ng-options to append/remove color objects to/from shirts.color?

I want to associate scope.color objects to scope.shirts.color objects so that if I change something like name of the color or code of the color, then the corresponding items in the associated color objects in shirts.colors should also get updated automatically.

From what I know about ng-options and ng-model, I will have to create new objects for colors and set its values based on what is selected in the select box, but those objects will be independent of the color objects and changing the color objects will not update the corresponding objects in shirts.

Thank you in advance for your responses.

like image 646
Gunjan Karun Avatar asked Dec 13 '25 05:12

Gunjan Karun


1 Answers

You can use ng-options for that directly:

Color: <select multiple ng:model="shirt.colors" ng:options="c.value as c.label for c in colors"></select>

Here is a Plunker: http://plnkr.co/edit/FQQxrSE89iY1BnfumK0A?p=preview

update

And about editing of source colors: if in shirt's color you store just value, it would be extremely hard to detect what was item was changed and re-select it in options (changed selected item unselects because AngularJS don't know reason of change).

As workaround you can select objects, not values. I've updated plunker.

like image 185
Valentyn Shybanov Avatar answered Dec 15 '25 06:12

Valentyn Shybanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!