检测角度JS中模型的特定元素的更改

时间:2015-03-28 13:23:48

标签: angularjs ng-repeat

我希望如此,如果用户编辑会员编号或角色,则推送保存特定行被请求发布到我的API,

http://plnkr.co/edit/plM45Ulwl2zKLFdPsKPl?p=preview

<tr ng-repeat="user in users" id="{{ user.userId}}">
    ..
    <td>{{ user.name}}</td>
    <td>{{ user.email}}</td>
    <td ng-click="editMemNo = !editMemNo" ng-show="editMemNo">
       {{ user.role}}  
    </td>
    ..
   <button> Save</button>
 ..
</tr>

angular.module("userList", []).controller("usersCtrl", function($scope) {

  var original = [{
    "userId": "1",
    "memNo": "1",
    "name": "asdf",
    "username": "max",
    "email": "max@gmail.com",
    "role": "10",
    "mobile": "079951334"
  },

  ..

  }];

  $scope.users = angular.copy(original);
  $scope.original = angular.copy(original);

  $scope.editMemNo = false;

  $scope.editMemNo = function() {
    $scope.editMemNo = true;
  };

  $scope.roles = ["1", "2", "9", "10"];

基本上我想在按钮上添加一个ng-click,这样当我点击它时,它只会将该行发送到数据库,条件是它已被改变(即脏状态)。所以我可以添加一个函数,比如

$scope.submitRow = function( the row I want  ){

     $http.post bla bla

};

并在按钮中我会

 <button ng-click="sumbitRow(What do I put here?)"

所以我认为我的问题基本上是什么,我坚持使用ng-click的submitRow参数?和或是做我想达到的目标的最佳方式?

2 个答案:

答案 0 :(得分:1)

你可以使用$ scope。$ watch,它允许你观察一个对象的一个​​特定属性并将回调绑定到该事件。

http://fdietz.github.io/recipes-with-angular-js/controllers/responding-to-scope-changes.html

编辑:我再次阅读了这个问题。它仍然有点不清楚你要求的是什么,但要获得对象的差异,试试这个: https://github.com/flitbit/diff

答案 1 :(得分:0)

我现在有点做了,我现在觉得很蠢

按钮......

    <button class="btn btn-success" ng-click="pushRow($index)">

代码......

$scope.pushRow = function($index){

    alert( "Lets say that we have posted this to the database " + JSON.stringify( $scope.users[$index] ));

};