带阵列的角度ng模型

时间:2015-01-12 22:12:25

标签: javascript angularjs angular-ngmodel

我试图让用户选择向表单添加文本字段,目前我已经设置了这样的控制器

  $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();

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

1 个答案:

答案 0 :(得分:1)

你根本不应该在这里进行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();
});