AngularJS实现表格数据的编辑,更新和删除

效果

实现

首先,我们先建立一些数据,当然你可以从你任何地方读出你的数据

var app = angular.module('plunker', ['ui.bootstrap']);
app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
  $scope.employees =[{id:101, name:'John', phone:'555-1276'},
                   {id:102, name:'Mary', phone:'800-1233'},
                   {id:103,name:'Mike', phone:'555-4321'},
                   {id:104,name:'Adam', phone:'555-5678'},
                   {id:105,name:'Julie', phone:'555-8765'},
                   {id:106,name:'Juliette', phone:'555-5678'}];
$scope.showEdit = true;
 $scope.master = {};
});

因为我们没有用到angular的bootstrap.这里,我们可以直接

var app = angular.module('plunker',[]);
<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>

    <script data-require="angular.js@1.2.x" src="http://code.angularjs.org/1.2.13/angular.js" data-semver="1.2.13"></script>

    <script src="jquery-1.11.0.min.js"></script>
    <script src="ui-bootstrap-tpls-0.10.0.min.js"></script>
    <script src="bootstrap.js"></script>
    <script src="app.js"></script>
    <link rel="stylesheet" href="bootstrap.css" />
    <link rel="stylesheet" href="mycss.css" />
  </head>

  <body ng-controller="MainCtrl">
    <h2>Inline Edit</h2>
    <!--<input id="test" value="ddd"/>-->
    <table>
      <tr>
        <th>name</th>
        <th>phone</th>
        <th></th>
      </tr>
      <tr ng-repeat="employee in employees">
        <td>
          <input type="text" id='txt_name_{{employee.id}}' ng-model="employee.name" class="inactive" readonly />
        </td>
        <td> <input type="text" ng-model="employee.phone" class="inactive" readonly /></td>
        <td><edit ng-Model="employee" ng-show="showEdit"><a>Edit</a></edit>
            <update ng-Model="employee" ng-show="!showEdit"><a>Update</a></update>
            <cancel ng-Model="employee" ng-show="!showEdit"> | <a>Cencel</a></cancel>
          | <delete ng-Model="employee"><a>Delete</a></delete>
        </td>
      </tr>
    </table>
  </body>
</html>

我们来看其中一个标签,<edit>,这里呢,我们用ng-Model来绑定employee这个对象。

这里,我们用angular的directive来对着三个标签进行事件的绑定。

angular的dirctive主要作用于DOM对象,而且他可以对Element Name (比如<edit></edit>)  对应于E:)、Attribute(比如<mytag edit=”express”></mytag> 对应于A、

Comment <!--   my comment –>  对应于M、Class <link class=”mycssclass”></link> 对应于C)。

默认对Attribute (A),

当我们有

app.directiv("edit", function(){

return{

restrict: "E",

. . . .

}

});

意思是说,我们要找到叫Element=”edit”的DOM对象,这里就是<edit>,

当然你也可以携程 restrict: “AE”,那意思就是说要找到Element或者attribute = edit的DOM对象

这里你可以随便对AEMC进行组合。

当你找到之后呢,就要对这个DOM进行操作,对于我们来说,就是对他绑定一个click的事件

app.directive("edit", function(){
  return{
    restrict: "E",
    link: function(scope,element){
      element.bind("click",function(e){
        alert("I am clicked for editing");
      });
    }
  }
})

这个时候呢,当你点Edit的时候呢,click事件就会触发。

再往下呢就是对edit click事件的延伸,我们要得到employee name的inputbox,然后对他进行css的转换,比如当你click edit后,应该出现inputbox的css的inactive或者active的调整,并且移除readOnly

这里要注意一件事,就是angular.copy,为什么使用angular.copy?这个是为后面的cancel做准备的,当你放弃修改的时候,你希望你的值恢复成原样,这个时候,对于angularJS来说,是要对model恢复原样。如何恢复修改之前的model?最简单的方法就是创建一个$scope.master = {}空的对象,然后在你click edit之后,马上把还没改变的model拷贝到这个空的master中去,把master作为一个临时的存储对象。

当我们click Edit之后,我们要隐藏Edit,而叫Update | Cancel出现。这个时候$scope.showEdit就用上了,在<edit>,<update>,<cancel>上面都有一个ng-show,这个flag用来指定这个元素是不是要显示。ng-show=”showEdit”这个值是绑定$scope.showEdit的。

app.directive("edit", function(){
  return{
    restrict: "E",
    link: function(scope,element){
      element.bind("click",function(e){
        alert("I am clicked for editing");
      });
    }
  }
})

下面,我们要给Update做事件的绑定。这里就没用什么可说的了。

app.directive("update",function($document){
  return{
    restrict: 'AE',
    require: 'ngModel',
    link: function(scope,element,attrs,ngModel){
      element.bind("click",function(){
         alert(ngModel.$modelValue + " is updated, Update your value here.");
         var id = "txt_name_" +ngModel.$modelValue.id;
         var obj = $("#"+id);
         obj.removeClass("active");
         obj.addClass("inactive");
         obj.attr("readOnly",true);
          scope.$apply(function(){
           scope.showEdit = true;
         })
      })
    }
  }
})

在下面就是Cancel了,上面说过了,Cancel的时候要还原之前的值,这个时候呢,我们就用angular.copy把当时临时存储的$scope.master拷贝回model去

app.directive("cancel",function($document){
  return{
    restrict: 'AE',
    require: 'ngModel',
    link: function(scope,element,attrs,ngModel){
      element.bind("click",function(){
         scope.$apply(function(){
           angular.copy(scope.master,ngModel.$modelValue);
           //console.log(ngModel.$modelValue);
         })

         var id = "txt_name_" +ngModel.$modelValue.id;
         var obj = $("#"+id);
         obj.removeClass("active");
         obj.addClass("inactive");
         obj.prop("readOnly",true);
          scope.$apply(function(){
           scope.showEdit = true;
         })
      })
    }
  }
});

最后就是Delete了,其实永远都要记住的事Angular是MVC,所以你这里你不用操心删除table行这样的事,只要删除model中emploee.id = @id就可以了

app.directive("delete",function($document){
  return{
    restrict:'AE',
    require: 'ngModel',
    link:function(scope, element, attrs,ngModel){
      element.bind("click",function(){
        var id = ngModel.$modelValue.id;
        alert("delete item where employee id:=" + id);
        scope.$apply(function(){
          for(var i=0; i<scope.employees.length; i++){
            if(scope.employees[i].id==id){
               console.log(scope.employees[i])
               scope.employees.splice(i,1);
            }
          }
          console.log(scope.employees);
        })
      })
    }
  }
});

基本上就完工了。这里我没有用任何现成的angular 插件,这只是对angular基本原理的阐述,如有误导或者有能简单的方法请指教。

AngularJS进阶(十一)AngularJS实现表格数据的编辑,更新和删除的更多相关文章

  1. 09Microsoft SQL Server 表数据插入,更新,删除

    Microsoft SQL Server 表数据插入,更新,删除 向表中插入数据 INSERT INTO insert into tb1 values(0004,'张凤凤') insert into ...

  2. 09Oracle Database 数据表数据插入,更新,删除

    Oracle Database 数据表数据插入,更新,删除 插入数据 Insert into table_name(column) values(values); insert into studen ...

  3. MYSQL数据插入、更新及删除

    上文讲到创建数据表,本文介绍create table后的数据插入: 一.通过insert into ...values...插入 insert into tablename (column1,colu ...

  4. SQL Server索引进阶:第十三级,插入,更新,删除

    在第十级到十二级中,我们看了索引的内部结构,以及改变结构造成的影响.在本文中,继续查看Insert,update,delete和merge造成的影响.首先,我们单独看一下这四个命令. 插入INSERT ...

  5. AngularJS进阶(十)AngularJS改变元素显示状态

    AngularJS改变元素显示状态 前言 本文描述使用AngularJS提供的ng-show和ng-hide指令实现自动监听某布尔型变量来改变元素显示状态. 控制html元素显示和隐藏有n种方法:ht ...

  6. AngularJS进阶(二)AngularJS路由问题解决

    AngularJS路由问题解决 遇到了一个棘手的问题:点击优惠详情时总是跳转到药店详情页面中去.再加一层地址解决了,但是后来发现问题还是来了: Could not resolve 'yhDtlMain ...

  7. AngularJS进阶(六)AngularJS+BootStrap实现弹出对话框

    AngularJS+BootStrap实现弹出对话框 参考资料: http://angular-ui.github.io/bootstrap/#/modal https://www.zybuluo.c ...

  8. 如何用angularjs制作一个完整的表格之五__完整的案例

    由于本人也是边学边写,因此整理的比较乱,下面放出我例子的完整代码,方便大家交流测试,如有问题欢迎评论 首先,表格采用的是BootStrap样式编辑的,主要使用的是angularjs,为了方便也有jQu ...

  9. angularJS进阶阶段(4)

    angularJS进阶阶段(4) 编译器/$compile 编译器$compile是一个AngularJS的内置服务,它负责遍历DOM树来查找匹配指令, 并调用指令的实现代码进行处理. HTML编译包 ...

随机推荐

  1. Dynamics CRM2016 Update or Create parentcustomerid in Contact using web api

    联系人实体中有个特殊的字段parentcustomerid 在通过web api创建或更新记录时,如果在给这个字段赋值时当做查找字段对待的话,那你就会遇到问题了,报错信息如下 正确的赋值方式如下

  2. Android源码浅析(六)——SecureCRT远程连接Linux,配置端点和字节码

    Android源码浅析(六)--SecureCRT远程连接Linux,配置端点和字节码 需要编译源码的同学,一般都是win+虚拟机吧,但是再虚拟机里体验并不是很好,所有市面上有很多的软件能够做到在wi ...

  3. springMVC源码分析--AbstractDetectingUrlHandlerMapping(五)

    上一篇博客springMVC源码分析--AbstractUrlHandlerMapping(三)中我们介绍了AbstractUrlHandlerMapping,主要介绍了一个handlerMap的ur ...

  4. ORACLE异常(整理网上资料)

    一.oracle预定义异常 命名的系统异常 产生原因 Oracle Error SQLCODE Value ACCESS_INTO_NULL 未定义对象 ORA-06530  -6530 CASE_N ...

  5. TensorFlow与OpenCV,读取图片,进行简单操作并显示

    TensorFlow与OpenCV,读取图片,进行简单操作并显示 1 OpenCV读入图片,使用tf.Variable初始化为tensor,加载到tensorflow对图片进行转置操作,然后openc ...

  6. android 网络工具 之Android-Volley的demo

    1.今天详细的研究了Volley的使用,下面来给大家介绍一下: Android Volley 是Google开发的一个网络lib,可以让你更加简单并且快速的访问网络数据.Volley库的网络请求都是异 ...

  7. J2EE进阶(十四)超详细的Java后台开发面试题之Spring IOC与AOP

    J2EE进阶(十四)超详细的Java后台开发面试题之Spring IOC与AOP 前言   搜狐畅游笔试题中有一道问答题涉及到回答谈谈对Spring IOC与AOP的理解.特将相关内容进行整理.    ...

  8. 1.Cocos2dx 3.2中vector,ValueMap,Touch触摸时间的使用.iconv字符编解码

     Cocos2dx3.2以后使用Vector<T>代替了CCArray.案例如下: 头文件:T02Vector.h #ifndef __T02Vector_H__ #define __ ...

  9. Struts 1 之文件上传

    Struts 1 对Apache的commons-fileupload进行了再封装,把上传文件封装成FormFile对象 定义UploadForm: private FormFilefile; //上 ...

  10. hbase高性能读取数据

    有时需要从hbase中一次读取大量的数据,同时对实时性有较高的要求.可以从两方面进行考虑:1.hbase提供的get方法提供了批量获取数据方法,通过组装一个list<Get> gets即可 ...