Created
May 4, 2016 05:22
-
-
Save paulstatezny/33658b0220a2bdb6d7354a6dfc8c68f6 to your computer and use it in GitHub Desktop.
Proof of Concept for defining scope properties in Angular as functions, taking a more FP approach.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<script type="text/javascript" src="https://code.angularjs.org/1.5.5/angular.js"></script> | |
</head> | |
<body> | |
<div ng-app="TestApp"> | |
<div test-directive> | |
<p>Number is {{number}}</p> | |
<p>Number is greater than 5: {{greaterThan5 ? 'true' : 'false'}}</p> | |
<button ng-click="pickNumber()">Pick a Number</button> | |
</div> | |
</div> | |
<script type="text/javascript"> | |
angular.module('TestApp', []) | |
.config(function($provide) { | |
$provide.decorator('$rootScope', function($delegate) { | |
$delegate.$$definitions = {}; | |
$delegate.$define = function(property, definition) { | |
this.$$definitions[property] = definition; | |
}; | |
$delegate.$update = function(changes) { | |
for (var key in changes) { | |
this[key] = changes[key]; | |
} | |
for (var key in this.$$definitions) { | |
var result = this.$$definitions[key](); | |
if (this[key] !== result) { | |
this[key] = result; | |
} | |
} | |
}; | |
return $delegate; | |
}) | |
}) | |
.directive('testDirective', function() { | |
return { | |
controller: function($scope) { | |
$scope.$define('greaterThan5', function() { | |
return $scope.number > 5; | |
}); | |
$scope.pickNumber = function() { | |
$scope.$update({ | |
number: Math.random() * 10 | |
}); | |
}; | |
} | |
}; | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment