3

作为一个人为的例子,假设我有一个看起来像这样的角度控制器:

function OverflowController($scope) {

  // initialize the count variable
  $scope.count = 0;

  // pretend the overflow logic is complex and doesn't belong in a filter or view
  var count = parseInt($scope.count);

  if (count < 100) {
    $scope.overflow = "normal";
  }
  else if (count < 200) {
    $scope.overflow = "warning";
  }
  else {
    $scope.overflow = "error";
  }

};

我有一个看起来像这样的视图:

<input ng-model="count">
<p>Count: {{count}}</p>
<p>Overflow? {{overflow}}</p>

如何将范围的溢出属性绑定到计数属性,以便在更新计数时,溢出也会自动更新?

4

3 回答 3

4

使用 $watch: ( http://docs.angularjs.org/api/ng.$ro​​otScope.Scope# $watch )

function OverflowController($scope) {

  // initialize the count variable
  $scope.count = 0;

  $scope.$watch('count', function (count) {
     // pretend the overflow logic is complex and doesn't belong in a filter or view

     if (count < 100) {
       $scope.overflow = "normal";
     }
     else if (count < 200) {
       $scope.overflow = "warning";
     }
     else {
       $scope.overflow = "error";
     }
   });
};
于 2013-07-12T20:37:29.210 回答
0

只需使用 getOverflow 作为 $scope 函数:

<div ng-controller="OverflowController">
<input ng-model="count" />
<p>Count: {{count}}</p>
<p>Overflow? {{getOverflow()}}</p>

angular.module('myApp', [])
    .controller("OverflowController", function ($scope) {
    // initialize the count variable
    $scope.count = 0;   
    $scope.getOverflow = function () {
         var count = parseInt($scope.count);
        var overflow = "error";
        if (count < 100) {
           overflow = "normal";
        } else if (count < 200) {
            overflow = "warning";
        }
        return overflow;
    }
});

JSFiddle:http: //jsfiddle.net/alfrescian/Gt9QE/

于 2013-07-12T20:46:02.730 回答
0

一个简单的方法是观察它的变化:

  $scope.$watch('count', function(newVal, oldVal) {
    if (!angular.equals(newVal, oldVal)) {
       updateCount();
    }
  });

  function updateCount() {
    var count = parseInt($scope.count);

    if (count < 100) {
      $scope.overflow = "normal";
    }
    else if (count < 200) {
      $scope.overflow = "warning";
    }
    else {
      $scope.overflow = "error";
    }
  }
于 2013-07-12T20:38:25.343 回答