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

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

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

Copy
angular.module('getterSetterExample', []) .controller('ExampleController', ['$scope', function($scope) { var _name = 'Brian'; $scope.user = { name: function(newName) { return angular.isDefined(newName) ? (_name = newName) : _name; } }; }]);
Growing Rails Applications in Practice
Check out our new e-book:
Learn to structure large Ruby on Rails codebases with the tools you already know and love.

Owner of this card:

Avatar
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