Read more

AngularJS: Binding to Perl-style getter/setters functions

Henning Koch
January 13, 2015Software engineer at makandra GmbH

Angular 1.3+ has an alternative getter/setter pattern: You can bind ng-model to an accessor function. This is a function that is either a getter (when it gets no arguments) or a setter (when it gets the new value as an argument):

$scope.name = function(newName) {
  return angular.isDefined(newName) ? (_name = newName) : _name;
}
Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

You need to bind this function with ng-model and ng-model-options="{ getterSetter: true } to activate this behavior.

Note that since this executes a function on every read, this is slower than a dumb property.

Full example

Full example from the docs Show archive.org snapshot :

<div ng-controller="ExampleController">
  <form name="userForm">
    Name:
    <input type="text" name="userName"
           ng-model="user.name"
           ng-model-options="{ getterSetter: true }" />
  </form>
  <pre>user.name = <span ng-bind="user.name()"></span></pre>
</div>

The JS that goes with it:

angular.module('getterSetterExample', [])
.controller('ExampleController', ['$scope', function($scope) {
  var _name = 'Brian';
  $scope.user = {
    name: function(newName) {
      return angular.isDefined(newName) ? (_name = newName) : _name;
    }
  };
}]);
Posted by Henning Koch to makandra dev (2015-01-13 22:58)