adding watch for an editable row in angularjs

854 views Asked by At

I am using xeditable for editing a table row in angular js. HTML Code is shown below.

<tr ng-repeat="expense in viewModel.expenses">
<td>{{expense.eid}}</td>
<td><span editable-text="expense.billAmt" e-ng-model="editForm.billAmt" e-name="billAmt" e-form="rowform">{{expense.billAmt}}</span></td>
<td><span ng-show="!rowform.$visible">{{expense.split}}</span><input type="text" ng-show="rowform.$visible" class="form-control input-sm" e-ng-model="editForm.split" ng-disabled="true" /></td>      

I want to update the 'split' value in last column when the value in 'billAmt' changes. So I add a watch in angularjs but is not updating.

$scope.$watch('editForm.billAmt',function(newValue,oldValue) {
    $scope.editForm.split=newValue/$scope.viewModel.members.length;
});

Is there any other way to add a watch while using xeditable?? How can I solve this?

1

There are 1 answers

2
MarcinPraski On BEST ANSWER

I'd refrain from using $scope.$watch() and turn to a more efficient solution. You can use the e-ng-change directive to fire a function computing new value of $scope.editForm.split every time the billAmt value changes. It would look like this:

<tr ng-repeat="expense in viewModel.expenses">
<td>{{expense.eid}}</td>
<td><span editable-text="expense.billAmt" e-ng-model="editForm.billAmt" e-name="billAmt" e-form="rowform" e-ng-change="checkSplit();">{{expense.billAmt}}</span></td>
<td><span ng-show="!rowform.$visible">{{expense.split}}</span><input type="text" ng-show="rowform.$visible" class="form-control input-sm" e-ng-model="editForm.split" ng-disabled="true" /></td>  

And in your controller add function checkSplit():

$scope.checkSplit = function(){
    $scope.editForm.split = $scope.editForm.billAmt / $scope.viewModel.members.length;
}

The checkSplit() function is invoked explicitly in a response to a event of value change, whereas $scope.$watch() handler runs on every digest cycle, so you can technically save some performance too.