angular-schema-form中的计算值

时间:2015-03-26 04:55:52

标签: angularjs angular-schema-form

我有一个用于输入一堆值的表单。我想在值上显示各种计算,但是要动态显示,以便在更改数字时立即更新结果。我认为这应该有用,但它没有 - 即计算永远不会运行:

angular.module('calcs', ['schemaForm'])
  .controller('CalcCtrl', function ($scope) {
    $scope.schema = {
      type: 'object',
      properties: {
        width: {
          type: 'number',
          title: 'Width'
        },
        depth: {
          type: 'number',
          title: 'Depth'
        }
      }
    };
    $scope.form = ['*'];
    $scope.model = {};

    $scope.$watch('[model.width, model.depth]', function() {
      // This function is never called
      $scope.area = $scope.model.width * $scope.model.depth;
    });
  });

我见过this question,但是我做了很多计算,我真的不想为每个人创建一个指令,所以我希望还有另一种方法。作为参考,这是我的模板:

<div ng-controller="CalcCtrl">
  <form sf-schema="schema" sf-form="form" sf-model="model"></form>
  <p>Area: {{area}}</p>
</div>

1 个答案:

答案 0 :(得分:5)

我相信你想要的是$watchCollection

$scope.$watchCollection('[model.width, model.depth]', function() {
  // This function is never called
  $scope.area = $scope.model.width * $scope.model.depth;
});

例如:

var app = angular.module('app', []);

app.controller('myController', function($scope) {

  $scope.model = {}
  
  $scope.$watchCollection('[model.width,model.height]', function() {
    $scope.area = $scope.model.width * $scope.model.height;
  });
  
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="myController">
    <input ng-model="model.width">
    <input ng-model="model.height">
    {{area || ''}}
  </div>
<div>

相关问题