AngularJS: Binding to Perl-style getter/setters functions

Posted Over 9 years ago. Visible to the public.

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

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;
    }
  };
}]);
Henning Koch
Last edit
2 months ago
Henning Koch
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2015-01-13 21:58)