1

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

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;
    });
  });

我已经看到了这个问题,但是我正在做很多计算,我真的不想为每个计算都创建一个指令,所以我希望有另一种方法。作为参考,这是我的模板:

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

1 回答 1

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>

于 2015-03-26T05:02:33.017 回答