Skip to content

Instantly share code, notes, and snippets.

@jsteenkamp
Created November 3, 2015 20:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsteenkamp/255f02fede1d9538533e to your computer and use it in GitHub Desktop.
Save jsteenkamp/255f02fede1d9538533e to your computer and use it in GitHub Desktop.
Replace Angular 1.x two-way binding with one-way binding
/*
Using one-way data bindings may offer an easy way to make sure such reassignments don't happen by accident.
If the component indeed does reassign the value on purpose, an explicit output binding should be used instead
of piggybacking on the two-way input.
- Replace a two-way '=' binding on the directive configuration with an expression binding '&'.
- Change all accesses to the binding inside the component to function calls.
http://teropa.info/blog/2015/10/18/refactoring-angular-apps-to-components.html
Component is used like this:
<search-field
search-term="mainCtrl.searchTerm"
on-search-term-change="mainCtrl.setSearchTerm(newSearchTerm)">
</search-field>
*/
module.directive('searchField', function() {
return {
scope: {},
controller() {
this.searchTerm = this.inputSearchTerm();
this.onChange = () => {
this.onSearchTermChange({newSearchTerm: this.searchTerm});
};
},
controllerAs: 'ctrl',
bindToController: {
inputSearchTerm: '&',
onSearchTermChange: '&'
},
templateUrl: `<input type="search"
ng-model="ctrl.searchTerm"
ng-change="ctrl.onChange()"/>`
};
});
/*
Like other kinds of state mutation, two-way bindings may make it unclear when and how things change in your application.
Traditional component with two-way binding and is used like this:
<search-field search-term="mainCtrl.searchTerm"></search-field>
*/
module.directive('searchField', function() {
return {
scope: {},
controller() {
// controller does not do anything
},
controllerAs: 'ctrl',
bindToController: {
searchTerm: '='
},
templateUrl: `<input type="search" ng-model="ctrl.searchTerm"/>`
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment