angularjs 实现动态添加控件

来源:互联网 发布:星光网络摄像机 编辑:程序博客网 时间:2024/06/10 04:34

实现下面这样的需求:


点击增加一块数据盘,会出现数据盘选项。


(1)最开始,想到原生javascript,jquery (appendChild()等方法结合angularjs来添加新的元素。但是突然发现控件里面的数据绑定,原生javascript没法控制。

(2)网查资料,找到$compile服务,动态改变html内容。本以为这可以解决我的需求,但是仔细研究发现$compile是这样的东西。

用$compile服务创建一个directive ‘compile’,这个complie会将传入的html字符串或者DOM转换为一个template,然后直接在html里调用compile即可




(3)$compile不能满足我的需求,继续找资料,才发现angularjs实现这样的需求,如此简洁明朗。即ng-repeat  $index.

<div ng-repeat="item in DATA.data">       <div class="form-group">       <div class="col-md-12">           <label class="col-md-1" >{{$index + 1}}</label>           <div class="col-md-9"><input type="text" class="form-control" ng-model="item.value" name="item{{$index + 1}}" /></div>           <div><input type="button" ng-click="item.delete($index)" value="删除"></div>       </div>       </div></div<div><input type="button" ng-click="add()" value="增加"></div>


testModule.controller('testController',     function ($scope, $log) {         $scope.DATA = new Object();         $scope.DATA.data = [{key: 0, value: ""}];         // add         $scope.add = function($index) {                              // 用时间戳作为每个item的key                          $scope.DATA.data.splice($index + 1, 0,{key: new Date().getTime(), value: ""});               }         // delete         $scope.DATA.delete = function($index) {                      $scope.DATA.data.splice($index, 1);        }});


0 0
原创粉丝点击