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

时间:2016-08-06 08:20:34

标签: javascript angularjs

我有一个选择框。我希望在“添加新内容”中生成相同的内容。按钮单击。

查看

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

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

2 个答案:

答案 0 :(得分:2)

如果你有

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

}])

答案 1 :(得分:0)

AngularJS views只是model reflection,其范围仅适用于数据展示。这意味着您永远不需要手动复制DOM元素,您只需要对绑定模型进行操作。

&#13;
&#13;
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])
;
&#13;
<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>
&#13;
&#13;
&#13;