Programing

AngularJS에서 동적 모델 이름을 어떻게 설정할 수 있습니까?

lottogame 2020. 9. 9. 18:56
반응형

AngularJS에서 동적 모델 이름을 어떻게 설정할 수 있습니까?


몇 가지 동적 질문으로 양식을 채우고 싶습니다 ( 여기에 바이올린 ).

<div ng-app ng-controller="QuestionController">
    <ul ng-repeat="question in Questions">
        <li>
            <div>{{question.Text}}</div>
            <select ng-model="Answers['{{question.Name}}']" ng-options="option for option in question.Options">
            </select>
        </li>
    </ul>

    <a ng-click="ShowAnswers()">Submit</a>
</div>
function QuestionController($scope) {
    $scope.Answers = {};

    $scope.Questions = [
    {
        "Text": "Gender?",
        "Name": "GenderQuestion",
        "Options": ["Male", "Female"]},
    {
        "Text": "Favorite color?",
        "Name": "ColorQuestion",
        "Options": ["Red", "Blue", "Green"]}
    ];

    $scope.ShowAnswers = function()
    {
        alert($scope.Answers["GenderQuestion"]);
        alert($scope.Answers["{{question.Name}}"]);
    };
}​

평가 된 Answers [ "GenderQuestion"] 대신 모델이 문자 그대로 Answers [ "{{question.Name}}"] 인 것을 제외하면 모든 것이 작동합니다. 모델 이름을 어떻게 동적으로 설정할 수 있습니까?


http://jsfiddle.net/DrQ77/

간단히 javascript 표현식을 ng-model.


이와 같은 것을 사용할 수 scopeValue[field]있지만 필드가 다른 개체에 있으면 다른 솔루션이 필요합니다.

모든 종류의 상황을 해결하려면 다음 지시문을 사용할 수 있습니다.

this.app.directive('dynamicModel', ['$compile', '$parse', function ($compile, $parse) {
    return {
        restrict: 'A',
        terminal: true,
        priority: 100000,
        link: function (scope, elem) {
            var name = $parse(elem.attr('dynamic-model'))(scope);
            elem.removeAttr('dynamic-model');
            elem.attr('ng-model', name);
            $compile(elem)(scope);
        }
    };
}]);

HTML 예 :

<input dynamic-model="'scopeValue.' + field" type="text">

내가 한 일은 다음과 같습니다.

컨트롤러에서 :

link: function($scope, $element, $attr) {
  $scope.scope = $scope;  // or $scope.$parent, as needed
  $scope.field = $attr.field = '_suffix';
  $scope.subfield = $attr.sub_node;
  ...

따라서 템플릿에서 특정 하드 코딩 된 요소 (예 : "Answers"사례) 아래가 아니라 완전히 동적 이름을 사용할 수 있습니다.

<textarea ng-model="scope[field][subfield]"></textarea>

도움이 되었기를 바랍니다.


To make the answer provided by @abourget more complete, the value of scopeValue[field] in the following line of code could be undefined. This would result in an error when setting subfield:

<textarea ng-model="scopeValue[field][subfield]"></textarea>

One way of solving this problem is by adding an attribute ng-focus="nullSafe(field)", so your code would look like the below:

<textarea ng-focus="nullSafe(field)" ng-model="scopeValue[field][subfield]"></textarea>

Then you define nullSafe( field ) in a controller like the below:

$scope.nullSafe = function ( field ) {
  if ( !$scope.scopeValue[field] ) {
    $scope.scopeValue[field] = {};
  }
};

This would guarantee that scopeValue[field] is not undefined before setting any value to scopeValue[field][subfield].

Note: You can't use ng-change="nullSafe(field)" to achieve the same result because ng-change happens after the ng-model has been changed, which would throw an error if scopeValue[field] is undefined.

참고URL : https://stackoverflow.com/questions/12553617/how-can-i-set-a-dynamic-model-name-in-angularjs

반응형