W
W
WhatIsHTML2017-03-15 15:36:40
JavaScript
WhatIsHTML, 2017-03-15 15:36:40

Why doesn't ng-options work inside ng-repeat?

There is a select that contains a list of products. Each item has its own price. When choosing a product, you must add the price of the product to the total price. At the same time, there can be several products, so the number of selects is regulated by drawing through ng-repeat. The select itself uses ng-options to render the products in the list. The problem is that when selecting a product in the select, this object does not fall into the $scope of the parent element. I don't understand how to solve.

<div ng-controller="ContactController">
    <div ng-repeat="item in featuresSelect track by $index" class="col-xs-12">
        <div class="row">
            <div class="col-xs-12 col-sm-9">
                <select ng-change="calcBudget()" name="budget" id="budget" ng-options="option as option.value for option in featuresOptions track by option.budget"
                    ng-model="selectedOption" required="required" style="width: 100%; height: 3.5vw; color: #a9a9a9;  padding: 10px 10px 10px 10px;">
            </select>
            </div>
            <div class="col-xs-12 col-sm-3 aligner">
                <div ng-if="$index == featuresSelect.length-1" class="btn btn_input btn_add" ng-click="addInput(featuresSelect, $index)"></div>
                <div ng-if="featuresSelect.length > 1" class="btn btn_input btn_remove" ng-click="removeInput(featuresSelect, $index)"></div>
            </div>
        </div>
    </div>
    <p>Selected option: {{selectedOption}} </p>
    <p>Total Price: {{price}}</p>
</div>

angular.module('WaikomWeb', []).controller('ContactController', function ($scope) {
    
    $scope.featuresSelect = [0];
    $scope.featuresOptions = [{
        value: "Custom Camera",
        budget: "4500"
    }, {
        value: "User posts",
        budget: "300"
    }, {
        value: "Face Recognition",
        budget: "10000"
    }, {
        value: "Video/Audio calls",
        budget: "700"
    }, {
        value: "Video/Audio playing",
        budget: "200"
    }];
    $scope.selectedOption ={};
    $scope.price = 0;
    $scope.addInput = function (array, index) {
        index++;
        array.push(index);
    }
    $scope.removeInput = function (array, index) {
        array.splice(index, 1);
    }
    $scope.calcBudget = function () {
        $scope.price += $scope.selectedOption.budget;
    }
});

UPD Live example
plnkr.co/edit/kzwP6M2D3IP0K3bsKaf8?p=preview

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mikhail Osher, 2017-03-15
@miraage

ngRepeat creates a new $scope.
Use components or "controller as" syntax, and don't get hung up on $scope at all.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question