Bringing functional UI paradigms to Angular 1.
Angular Dry Scope helps keep scope-management code DRY by allowing you to define the value of a scope property in one place, instead of updating it in disjointed parts of the code.
Install using NPM:
npm install angular-dry-scope --save
Then import it as a module in your Angular app:
angular.module('MyApp', ['dry-scope'])
$scope.$define('totalCost', function() {
var costBeforeTax = $scope.items.reduce(function(total, item) {
return total + item.cost;
}, 0);
return costBeforeTax * taxMultiplier;
});
Don't do this:
$scope.taxMultiplier = 1.08;
Instead, do this:
$scope.$update({
taxMultiplier: 1.08
});
And $scope.totalCost
will automatically be updated.
You're an informed Front End web developer. You know to avoid watchers and filters in Angular 1 because they cause performance problems. But you also know that functional programming paradigms (defining your app state using functions instead of "manually" modifying it) are very powerful and allow you to write applications that are easier to read, maintain, and change.
Angular Dry Scope allows you to define scope properties as definition functions that return the value of the property. Definitions are similar in intent, although different in mechanism, to watchers. Watchers say, "when this scope value changes, run this code." Definitions say, "this function will return the correct value of this property at any time." And every time the scope is updated via $update
, the definitions are re-run.
When $update
is called on a scope, all child scope definitions are re-run, ensuring that any definitions based on inherited scope properties are updated.
- If you
$define
a scope property, don't ever set it manually. - Within a component (directive/controller) that uses
$define
, always use$update
to set scope properties.
Feedback is always welcome! Please open up a GitHub issue if you find a problem.
Pull requests are welcome! I'll generally respond within a couple days. When the project needs more formal contribution documentation, I'll add it.
Feature requests are welcome, too. I'm specifically interested in expanding the idea of bringing functional UI to Angular 1. So I'll gladly entertain API changes.
This module is an experiment to examine the use of newer functional UI approaches in Angular 1. It was inspired by the state/props model of React.js. $update
was shamelessly based on React's setState
. Special thanks to @duhduhdan and Tyler Kayser for discussions and ideas that led to this project.