Posted over 4 years ago. Visible to the public.

AngularJS: Binding to Perl-style getter/setters functions

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):

$ = 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:

<div ng-controller="ExampleController"> <form name="userForm"> Name: <input type="text" name="userName" ng-model="" ng-model-options="{ getterSetter: true }" /> </form> <pre> = <span ng-bind=""></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; } }; }]);

By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.

Owner of this card:

Henning Koch
Last edit:
over 4 years ago
by Henning Koch
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more