【问题标题】:How to add `<input>` elements with button click AngularJS如何使用按钮单击AngularJS添加`<input>`元素
【发布时间】:2019-08-28 15:43:45
【问题描述】:

附加对象后如何实时使用ng-bind

我希望能够添加一个新元素并使用 ng-bind 属性来更改新元素的值。

我已经尝试了多种方法,请参阅下面的代码以了解我所能想到的最佳效果。

$(document).ready(function() {
  $("#create-input").click(function() {
    var newInput = document.createElement("p");
    var code = document.createElement("span");
    code.innerHTML = "{{input2}}";
    newInput.innerHTML = "<p>{input2}:&ensp;<input type='text' ng-model='name2'>&emsp; {{name2}}</p>";
    $("#target-container").append(newInput);
    $("#main-container").append(code);
  });
});

当我在新附加的输入中添加文本时,附加的 {{name2}} 值不会改变。我不明白为什么我无法在追加后通过文本输入框更改{{name2}}

【问题讨论】:

  • 这是因为当通过其他库附加内容以及加载 DOM 后,Angular 不起作用。这就是为什么在 Angular 中使用 jQuery 不是一个好习惯的部分原因。
  • 知道了。在您看来,Regex 会是更好的解决方案,还是只是 Vanilla JS?
  • 不,如果有更糟的话。我建议单独使用 Angular 来更新 DOM 中的内容。
  • 在 DOM 加载后有什么好的方法吗?
  • 你需要在 newInput 上调用 $compile,来自 angularjs。避免使用第三方库,创建指令/组件会更容易维护。

标签: javascript jquery angularjs


【解决方案1】:

使用ng-repeat 指令将输入元素添加到DOM:

angular.module("app",[])
.controller("ctrl",function($scope) {
    $scope.arr=[
       {name: "name1", value: ""}
    ];
    $scope.addInput = function() {
        $scope.arr.push( {
            name: "name" + ($scope.arr.length+1),
            value: ""
        })
    };
})
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app" ng-controller="ctrl" >
    <div ng-repeat="elem in arr">
       {{elem.name}}: 
        <input ng-model="elem.value">        
    </div>
    <button ng-click="addInput()">Add Input</button>
    <div>{{arr}}</div>
</body>

【讨论】:

    猜你喜欢
    • 2019-05-19
    • 1970-01-01
    • 1970-01-01
    • 2021-06-24
    • 2021-03-03
    • 2020-03-01
    • 1970-01-01
    • 2012-08-06
    • 1970-01-01
    相关资源
    最近更新 更多