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]">
여기 동작하고 있는 plunk가 있습니다.http://plnkr.co/edit/ALHQtkjiUDzZVtTfLIOR?p=preview
편집 ng-change와 함께 이것을 사용하는 코멘트에 올바르게 기술된 바와 같이 "dummy" ng-model이 사전에 존재해야 합니다.단, 1.3에서는 필수 옵션이 프레임워크에 의해 제공되고 있는 것에 주목해야 한다.아래 https://stackoverflow.com/a/28365515/3497830를 확인해 주세요! /EDIT
더 복잡한 작업을 수행하다가 간단한 케이스에 걸려 넘어지는 저와 같은 경우를 대비해서, 저는 임의의 식을 ng-model에 동적으로 바인드하기 위해 이 솔루션을 고안했습니다.http://plnkr.co/edit/ccdJTm0zBnqjntEQfAfx?p=preview
방법: 표준 각도식을 취하여 평가하고 결과를 ng-model 및 $compile을 통해 스코프에 링크하는 지시 dynamic Model을 만들었습니다.
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의 표현으로 사용되는 문자열이 됩니다.
나는 이것이 누군가가 이 해결책을 생각해내야 하는 두통을 덜어주기를 바란다.
안부 전해 주세요, 저스터스
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' 및 유틸리티(모델, '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>
언급URL : https://stackoverflow.com/questions/14183614/dynamically-assign-ng-model
'source' 카테고리의 다른 글
NSJONSerialization 사용방법 (0) | 2023.02.13 |
---|---|
angular-bootstrap 드롭다운이 닫히지 않도록 하는 방법(지령에 의해 바인딩된 이벤트 언바인드) (0) | 2023.02.13 |
MongoDB 데이터베이스 파일 크기 축소 (0) | 2023.02.13 |
JQuery를 사용하여 JSON 데이터를 게시하려면 어떻게 해야 합니까? (0) | 2023.02.13 |
AJAX 로드 후 Contact Form 7 Form에서의 AJAX의 이니블화 (0) | 2023.02.13 |