Paweł Durczok Paweł Durczok - 1 month ago 5
AngularJS Question

Comparing objects from two scopes to provide a value

I'll try to simplify the problem as much as I can.

Let's say I have 2 scopes

$scope.section1 = [
{label: 'label1'},
{label: 'label2'}
];

$scope.section2 = [
{value: 'one'},
{value: 'two}
];


Those scopes are used to generate buttons with ng-repeat

<button ng-repeat="item in section1 type="button">{{item.label}}</button>


and

<button ng-repeat="item in section2 type="button">{{item.value}}</button>


Now what I would like to do it to create a third scope that would attach values to the combinations of objects from the two previous ones, say:

$scope.combo = [
{ section1.label:label1 + section2.value: one = 'result1' },
{ section1.label:label2 + section2.value: one = 'result2' },
{ section1.label:label1 + section2.value: two = 'result3' },
{ section1.label:label2 + section2.value: two = 'result4' }
];


Now here comes the tricky part. What I would need to do, is to add a function that would take the values of clicked ng-repeat buttons from each section and then display the results based on the third scope in an input field or something.

So, if you click the button with label:label1 and the one with value:two the input field would show result3.

I'm very green when it comes to Angular and I have no idea how to approach it, especially that all values are strings.

Answer

If I understand correctly you could setup your combo something like ...

$scope.combo = {
    "label1": {
        "one": "result1",
        "two": "result2"
    },
    "label2": {
        "one": "result3",
        "two": "result4"
    }
}

You can then reference the correct value as combo[valueFromButton1][valueFromButton2] where valueFromButton1 and valueFromButton2 point at a model that contains the result of the clicked buttons. Your controller function then just needs to tie everything together by updating the model when the buttons are clicked.

See this plunkr ... https://embed.plnkr.co/GgorcM/

Comments