使用数组的AngularJS ng模型

lndjwyie  于 2023-09-30  发布在  Angular
关注(0)|答案(1)|浏览(146)

我试图让用户选择添加文本字段的形式,目前我已经建立了我的控制器这样

$scope.campaign = {name:"", question:"",answers:[]};
 var totalAnswers = 2;
var totalAnswerAdded = 0;
var utils = {
    initAnswerFields : function(){
        var answers = angular.element("#answer-fields");
        var input;
        console.log("ADDING");
        while(totalAnswerAdded < totalAnswers){
            $scope.campaign.answers.push({answer:""});
            input = angular.element("<input type='text' data-name='answer-"+totalAnswerAdded+"' data-ng-model='campaign.answers["+totalAnswerAdded+"].answer' />");
            answers.append(input);
            totalAnswerAdded++;
        }

    },
    addAnswerFields : function(){

    }
};
var init = function(){
    utils.initAnswerFields();
    utils.addAnswerFields();
};
init();

它按预期添加输入字段,但更改答案字段不会更新模型值。首先,这样做是可行的吗?如果是,我做错了什么。

6l7fqoea

6l7fqoea1#

您根本不应该在这里进行DOM操作(尤其是在您的控制器中)。Angular有ng-repeat来迭代数组/对象中的每个元素。因此,您应该设置视图以响应模型中的更改:

<div ng-controller="ctrl">
    <div ng-repeat="answer in campaign.answers">
        <input type="text" data-ng-model="answer.value">
    </div>
</div>

然后在控制器中更改视图将表示的数据:

app.controller('ctrl', function ($scope) {
    var totalAnswers = 2;
    var totalAnswerAdded = 0;

    $scope.campaign = {name:"", question:"",answers:[]};

    var utils = {
        initAnswerFields: function() {
            while(totalAnswerAdded < totalAnswers) {
                $scope.campaign.answers.push({value: ''});
                totalAnswerAdded++;
            }
        }
    };

    var init = function() {
        utils.initAnswerFields();
        utils.addAnswerFields();
    };

    init();
});

相关问题