LandonSchropp
LandonSchropp

Reputation: 10234

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?

Upvotes: 3

Views: 3652

Answers (3)

alfrescian
alfrescian

Reputation: 4079

just use getOverflow as $scope function:

<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/

Upvotes: 0

Karen Zilles
Karen Zilles

Reputation: 7661

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

Upvotes: 4

Terry
Terry

Reputation: 14219

A simple way would be to watch it for changes:

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

Upvotes: 0

Related Questions