robins robins - 3 months ago 11
Javascript Question

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.
I'm new.So Please help me.

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

Anyone can help me

Answer

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

UPDATED

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

}])
Comments