Angularjs custom directive to select

I am creating a custom directive called "combo". I pass parameters to it from the main controller, however I need to get the value selected from the parent controller.

Scenario:

Rendering:

I have an array called $ scope.fields that contains various types of controls that will be presented to the user. I loop around in this array to check the drawing of text input or combos.

Snap

$ scope.fieldValues will synchronize the values entered by the user. Entering text changes the value in fieldValues ​​[$ index] .value . Therefore, I can get the final values ​​from fieldValues ​​by specifying a relative index.

Problem

fieldValues ​​[$ index].value. .

 <script type="text/javascript">
   angular.module('myApp', [])

.controller('MyController', function ($scope) {
    $scope.fields = [{ name: 'customers', type: 'combo' }, { name: 'Name', type: 'text' }, { name: 'country', type: 'combo' }]
    $scope.fieldValues = [{ value: '' }, { value: '' }, { value: '' }];
    $scope.myItems = ['Item 1', 'Item 2'];
    $scope.itemId = 1;


    $scope.log = function () {
        for (var i = 0; i < $scope.fieldValues.length; i++) {
            if (!angular.isUndefined($scope.fieldValues[i].value))
                console.log($scope.fieldValues[i].value);
        }

    }
})
 
 
.directive('combo', function () {
    return {
        restrict: 'AE',
        template: '<div class="input-group"> <select ng-model="selectedItem" ng-change="changeEvent()" >' +
                    '<option ng-value="model" ng-repeat="model in items">{{model}}</option></select>' +
                    ' {{selectedItem}} </div>',
        replace: true,
        scope: {
            items: '=',
            defaultItem: '=',
            changeEvent: '&'
          
        },
        controller: function ($scope) {

        },
        link: function (scope, element, attrs) {

            scope.selectedItem = scope.items[scope.defaultItem];
            scope.changeEvent = function () {
                //console.log("changed");
                console.log(scope.selectedItem);
            }
        }
    };
});

    </script>
<body ng-app="myApp" ng-controller="MyController">
    <div ng-repeat="field in fields">
        <div ng-if="field.type == 'combo'">
            <strong>{{field.name}}</strong>
            <div combo items="myItems" default-item="itemId"></div>
        </div>
        <div ng-if="field.type == 'text'">
            <strong>{{field.name}}</strong>
            <input type="text" ng-model="fieldValues[$index].value" />
        </div>
    </div>

    <input type="button" value="log" ng-click="log()" />
</body>
Hide result
+4
1

plunker , : http://plnkr.co/edit/TEh9kauHCVfCPSw552c9?p=preview

, , fieldValues[$index].value.

!

+2

Source: https://habr.com/ru/post/1619383/


All Articles