Angular.js将一个属性绑定到另一个属性

时间:2013-07-12 20:34:13

标签: javascript angularjs

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

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>

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

3 个答案:

答案 0 :(得分:4)

使用$ watch:(http://docs.angularjs.org/api/ng.$rootScope.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";
     }
   });
};

答案 1 :(得分: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";
    }
  }

答案 2 :(得分: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/