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

how to fetch calculated ng-model value into an another ng-model

本文关键字:ng-model 获取 另一个 计算      更新时间:2023-09-26

我有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()
    };
  });
}); 

如果您还没有考虑过,可以在tripsheet对象上使用watch并计算watch中的值

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

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

你可以设置一个手表的总数…

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

小提琴

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

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

小提琴