如何将计算出的ng-model值提取到另一个ng模型中

时间:2014-06-04 19:37:22

标签: javascript angularjs

我有3 ng模型,我需要使用angularjs将前两个的计算数据提取到第三个

我试过这样的事,但没有工作

HTML

var urlt = 'http://localhost/tripsheets';
app.factory('tripsheetFactory', function ($http) {
  return {
    getTripsheets: function () {
      return $http.get(urlt + '/all');
    },
    addTripsheet: function (tripsheet) {
      return $http.post(urlt, tripsheet );
    },
    deleteTripsheet: function (tripsheet) {
      return $http.delete(urlt + '?id=' + tripsheet.id);
    },
    updateTripsheet: function (tripsheet) {
      return $http.put(urlt + '?id=' + tripsheet.id, tripsheet);
    }
  };
});

app.controller('TripsheetCtrl', function ($scope, tripsheetFactory) {

  $scope.tripsheets = [];
  $scope.getTotalCalc = function () {
    return $scope.tripsheets.cash*$scope.tripsheets.tax;
  };

  tripsheetFactory.getTripsheets().then(function(data){
    $scope.tripsheets = data.data;
    $scope.tripsheet = {
      tripsheet_num: $scope.tripsheets.length +1,
      cash:null,
      tax:null,
      total: $scope.getTotalCalc()
    };
  });
}); 

2 个答案:

答案 0 :(得分:0)

如果您还没有考虑过,请在tripheet对象上使用手表并计算手表中的值

$scope.$watch('tripsheets', function(val){
    $scope.tripsheets.total = $scope.tripsheets.cash*$scope.tripsheets.tax;
  }, true);

示例演示:http://plnkr.co/edit/Ml6eLM4vCYz3tPaL8j3n?p=preview

答案 1 :(得分:0)

您可以在总计上设置监视...

$scope.$watch(function() {
    return $scope.tripsheets.cash * $scope.tripsheets.tax;
 }, function(value) {
    $scope.tripsheets.total = value;
});

Fiddle

或者使用Object.defineProperty()(需要ES5 +)......

Object.defineProperty($scope.tripsheets, 'total', {
    get: function(){
        return $scope.tripsheets.cash * $scope.tripsheets.tax;
    }
});

Fiddle