繁体   English   中英

在Angular js中单击按钮时动态生成HTML

[英]Generate HTML dynamically on button click in Angular js

我有一个选择框。 我想在“添加新”按钮上生成相同的内容。

视图

<button id="sample_editable_1_new" class="btn sbold green" ng-mousedown="count = count + 1" ng-click="Get_toolNames()">Add New
  <i class="fa fa-plus"></i>
</button>

<select class="bs-select form-control" name="tool_id" ng-model="Tooldata.tool_name" ng-options="t.tm_id as t.tm_name for t in tools" required>
  <option value="">Select</option>
</select>

如何在此按钮单击上生成相同的内容?

如果你有

<button id="sample_editable_1_new" class="btn sbold green" ng-mousedown="count = count + 1" ng-click="buttonClick"> Add New
                                <i class="fa fa-plus"></i>
 </button>

在您的controller您可以注入并使用$compile服务。

$scope.buttonClick = function(){
   var el = angular.element(/* Here your element */);
   el.append( '<select class="bs-select form-control" name="tool_id" ng-model="Tooldata.tool_name"  ng-options="t.tm_id as t.tm_name for t in tools" required>' + 
                     '<option value="">Select</option>' + '</select>')
   $compile(el)($scope);
}

更改逻辑以获取所需的数据和元素:

有关更多信息,请参见$ compile

更新资料

var sample_2_tbody = angular.element('#sample_2 tbody');
$compile(sample_2_tbody)($scope);

如何在控制器中注入服务:

app.controller('MyController', ['$scope', '$compile', function($scope, $compile){

}])

AngularJS中, views只是model reflection ,其作用域仅用于数据表示 这意味着您不需要手动复制DOM元素,只需要对绑定模型进行操作即可。

 function TestCtrl($scope, select) { copy = () => angular.copy(select); $scope.selects = [copy()]; $scope.values = {}; $scope.add = () => { //$scope.selects.unshift(select); // add at the beginning $scope.selects.push(copy()); // add at the end }; } angular .module('test', []) .value('select', [{ id: 1, label: 'aLabel', subItem: { name: 'aSubItem' } }, { id: 2, label: 'bLabel', subItem: { name: 'bSubItem' } }]) .controller('TestCtrl', ['$scope', 'select', TestCtrl]) ; 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <section ng-app="test"> <article ng-controller="TestCtrl"> <button ng-click="add($event)">Add</button> <hr> <div ng-repeat="select in selects track by $index"> <select ng-model="values[$index]" ng-options="t as t.label for t in select"> </select> </div> <hr> <pre><code ng-bind="values | json"></code></pre> </article> </section> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM