Skip to content

Instantly share code, notes, and snippets.

@pmunin
Created October 28, 2015 00:40
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 pmunin/152d455dc26a19700869 to your computer and use it in GitHub Desktop.
Save pmunin/152d455dc26a19700869 to your computer and use it in GitHub Desktop.
Analogy of KnockoutJs With directive for AngularJs
// Analogy of KnockoutJs With directive http://knockoutjs.com/documentation/with-binding.html
// Implementation is based on that one: http://stackoverflow.com/questions/17300814/the-with-binding-of-knockoutjs-in-angularjs
myAngularApp
.directive('koWith', function () {
return {
restrict: 'A',
scope: true,
controller: function ($scope, $attrs, $parse) {
var ScopePropertyDesc = function (prop) {
var self = this;
self.propName = prop;
self.parsed = $parse(prop);
self.enumerable = true;
self.configurable = true;
self.get = function () {
var withObj = $scope.$parent[$attrs.koWith];
var res = self.parsed($scope.$parent, withObj);
return res;
};
self.set = function (newValue) {
var withObj = $scope.$parent[$attrs.koWith];
self.parsed.assign(withObj, newValue);
};
};
$scope.$parent.$watch($attrs.koWith, function (oldVal, newVal) {
var withObj = $scope.$parent[$attrs.koWith];
(function copyPropertiesToScope(withObj) {
for (var prop in withObj) {
if (withObj.hasOwnProperty(prop)) {
Object.defineProperty($scope, prop, new ScopePropertyDesc(prop));
}
};
})(withObj);
});
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment