简体   繁体   中英

Generate HTML dynamically on button click in Angular js

I have a select box. I want to generate the same on a 'Add New' button click.

View

<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>

How can I generate the same on this button click?

If you have

<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>

In your controller you can inject and use $compile service.

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

Change your logic to get the data and the element you want:

For more see $compile .

Update

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

How to inject a service in the controller:

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

}])

In AngularJS views are just a model reflection and their scope is only for data presentation . That's mean you never need to manually copy a DOM Element, you just need to operate on the bound model.

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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