Created
October 28, 2015 00:40
-
-
Save pmunin/152d455dc26a19700869 to your computer and use it in GitHub Desktop.
Analogy of KnockoutJs With directive for AngularJs
This file contains 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
// 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