Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular.js binding one property to another

As a contrived example, let's say I have an angular controller that looks something like this:

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

};

and I have a view that looks like this:

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

How can I bind the overflow property of the scope to the count property in such a way that when the count is updated, the overflow automatically gets updated too?

like image 749
LandonSchropp Avatar asked Aug 13 '26 18:08

LandonSchropp


1 Answers

Use $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";
     }
   });
};
like image 57
Karen Zilles Avatar answered Aug 15 '26 08:08

Karen Zilles



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!