[javascript] ng-model 동적 할당

개체 배열에서 확인란 집합을 생성하려고합니다. 체크 박스가 ng-model을 배열에 제출 될 새 개체의 속성에 동적으로 매핑하도록하는 것을 목표로하고 있습니다.

내가 염두에 두었던 것은

<li ng-repeat="item in items">
    <label>{{item.name}}</label>
    <input type="checkbox" ng-model="newObject.{{item.name}}">
</li>

이 JSFiddle에서 볼 수있는 것처럼 작동하지 않습니다.

http://jsfiddle.net/GreenGeorge/NKjXB/2/

아무도 도울 수 있습니까?



답변

원하는 결과를 얻을 수 있습니다.

<input type="checkbox" ng-model="newObject[item.name]">

다음은 작동하는 플렁크입니다. http://plnkr.co/edit/ALHQtkjiUDzZVtTfLIOR?p=preview


답변

편집
ng-change와 함께 이것을 사용하는 주석에서 올바르게 언급했듯이 “더미”ng-model이 미리 존재해야합니다. 그러나 1.3에서는 프레임 워크에서 필요한 옵션을 제공 한 것으로 보입니다. 아래 https://stackoverflow.com/a/28365515/3497830을 확인 하세요!
/편집하다

좀 더 복잡한 작업을하면서 간단한 경우에 걸림돌이되는 저와 같은 경우를 대비하여 ng-model에 동적으로 임의의 표현식을 바인딩하기 위해 고안 한 솔루션입니다. http://plnkr.co/edit/ccdJTm0zBnqjntEQfAfx?p = 미리보기

방법 : 표준 각도 표현식을 사용하여 평가하고 결과를 ng-model 및 $ compile을 통해 범위에 연결하는 dynamicModel 지시문을 만들었습니다.

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.data = {};
  $scope.testvalue = 'data.foo';
  $scope.eval = $scope.$eval;
});

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.data = {};
  $scope.testvalue = 'data.foo';
  $scope.eval = $scope.$eval;
});

app.directive('dynamicModel', ['$compile', function ($compile) {
    return {
        'link': function(scope, element, attrs) {
            scope.$watch(attrs.dynamicModel, function(dynamicModel) {
                if (attrs.ngModel == dynamicModel || !dynamicModel) return;

                element.attr('ng-model', dynamicModel);
                if (dynamicModel == '') {
                    element.removeAttr('ng-model');
                }

                // Unbind all previous event handlers, this is 
                // necessary to remove previously linked models.
                element.unbind();
                $compile(element)(scope);
            });
        }
    };
}]);

사용법은 단순히 dynamic-model = “angularExpression”입니다. 여기서 angularExpression은 ng-model의 표현식으로 사용되는 문자열을 생성합니다.

나는 이것이 누군가 가이 해결책을 찾아야하는 두통을 덜어주기를 바랍니다.

감사합니다, Justus


답변

Angular 1.3에서는 ng-model-options지시문을 사용 하여 모델을 동적으로 할당하거나 표현식에 바인딩 할 수 있습니다.

다음은 plunkr입니다 : http://plnkr.co/edit/65EBiySUc1iWCWG6Ov98?p=preview

<input type="text" ng-model="name"><br>
<input type="text" ng-model="user.name"
ng-model-options="{ getterSetter: true }">

ngModelOptions여기에 대한 자세한 정보 : https://docs.angularjs.org/api/ng/directive/ngModelOptions


답변

이것은 ‘model.level1.level2.value’와 같이 더 깊은 표현을 지원하는 나의 접근 방식입니다.

<input class="form-control" ng-model="Utility.safePath(model, item.modelPath).value">

여기서 item.modelPath = ‘level1.level2’및 Utility (model, ‘level1.level2’)는 model.level1.level2를 반환하는 유틸리티 함수입니다.


답변

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

    <div ng-app="myApp" ng-controller="myCtrl">
        <form name="priceForm" ng-submit="submitPriceForm()">
            <div ng-repeat="x in [].constructor(9) track by $index">
                <label>
                    Person {{$index+1}} <span class="warning-text">*</span>
                </label>
                <input type="number" class="form-control" name="person{{$index+1}}" ng-model="price['person'+($index+1)]" />

            </div>
            <button>Save</button>
        </form>
    </div>

    <script>
        var app = angular.module('myApp', []);
        app.controller('myCtrl', function ($scope) {
            $scope.price = [];
            $scope.submitPriceForm = function () {
                //objects be like $scope.price=[{person1:value},{person2:value}....]
                console.log($scope.price);
            }
        });
    </script>
</body>
</html>


답변