Angular JS is a front end framework that supports the MVC architecture design pattern. Within this framework, the model is changed by a controller who in turn tells the view what has changed in order to render an updated DOM, which in turn takes in data to be read again by the controller. Today I'll talk a little about Angular JS's getter and setter methods, how they are useful, and some warnings to heed.
Angular JS gives us a few ways to bind data being passed down through the modules of our program. Getters and setters are methods in Angular JS for taking some user input in the DOM and within our controller, retrieve and/or update the model with a passed in argument.
A getter method is just a function that returns a property on an object. The getter and setter is bound directly to the ng-model rather than a directive or using the bindings object. This is a great way to make various changes to requests within the controller that will be passed to the model with specific intentions.
Consider a user model. The form below takes in a username, that user name is passed to the model using a getter and setter, which uses its value as an argument to the options directive.
<div ng-controller="example-form-view">
<form name="new-user">
<label>Choose Name:
<input type="text" name="userName"
ng-model="user.name"
ng-model-options="{ getterSetter: 'hartsean' }" />
</label>
</form>
<pre>user.name = <span ng-bind="user.name()"></span></pre>
</div>
This is a way to access variables not in scope, and to manipulate the data being passed in to the view with arguments at call time. Although the above code seems fine and normal, as the getter and setter is performing a specific and necessary task for this context, it can become unwieldy in different forms.
The reason we use modular code and keep our code DRY as well as the point of having scope, is to keep our code private and functional. If there is more structure and intention built in to your app, you will probably rely less on getters and setters, as they can become cumbersome, and hard to trackdown and add complexity to the flow of logic on your app. Hiding a way an object gets manipulated is a principle that gets broken with this approach to handling the incoming data, but it's great to have the ability to get and set values on a model when needed.
Top comments (0)