从javascript设置ng-model值

时间:2016-04-07 15:34:28

标签: javascript angularjs

是否可以使用setAttribute方法或以任何其他方式设置输入文本框的ng-model值。 我有一个按钮,通过克隆html中的文本类型输入来添加文本框。但我无法弄清楚如何在创建文本框时设置ng-model,而是从按钮的onclick方法克隆。 PS:创建时,不同文本框的ng-model值不同。

更新
<!DOCTYPE html>
<html>
 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
 <script>
var add = function() {
    var txtClone = document.getElementById("textinput").cloneNode(true);
    txtClone.setAttribute("ng-model", "name");
    document.getElementById("target").appendChild(txtClone);
}
</script>
<body>
    <input type="text" id="textinput" placeholder="Enter name here">
    <div ng-app="">

        <p>Input something in the input box:</p>
        <p id="target">Name : <hr></p><button click="add()">Type</button>
        <h1>Hello {{name}}</h1>

    </div>

</body>
</html>

当我点击按钮(Type)时,我用ng-app克隆了div之外的输入文本 在那里,我尝试使用setAttribute ....设置克隆文本框的ng-model值,但它没有绑定。我的问题是,有什么办法可以从js脚本中设置这个ng-model值?

2 个答案:

答案 0 :(得分:3)

ng-model值通常只是范围变量,您可以在控制器中修改它。

示例:

在您看来:

<input type="text" ng-model="demoInput"></input>

在您的控制器中:

$scope.demoInput = "https://www.youtube.com/watch?v=dQw4w9WgXcQ";

在该示例中,只要您更改$scope.demoInput,文本框中的值就会更新以反映它。

即使使用ng-repeat迭代一组值生成输入,这也有效。

<div ng-repeat="text in demoInputs">
    <input type="text" ng-model="text"></input>
</div>

<div ng-repeat="text in demoInputs track by $index">
    <input type="text" ng-model="demoInputs[$index]"></input>
</div>

将与

一起使用
for(var i=0;i<somelength;i++)
    $scope.demoInputs[i] = 'At index ' + i;

答案 1 :(得分:3)

好的,如果我理解正确的话,你基本上将文本框添加到输入列表中。

你可以做几件事:

对象方式列表

说你有以下控制器:

app.controller('textBoxController', function () {

    this.textBoxList = [];

    this.addTextBox = function () {
        this.textBoxList.push({
            value: 0
        })
    }.bind(this)

});

以下html:

<div ng-controller="textBoxController as txtCTRL">

    <div ng-repeat="item in txtCTRL.textBoxList">
       <input type="text" ng-model="item.value">

    </div>

</div>
相关问题