pmunin
10/28/2015 - 12:40 AM

Analogy of KnockoutJs With directive for AngularJs

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);
            });
        }
    };
    });