The “with” binding of KnockoutJS in AngularJS ?

The “with” binding of KnockoutJS in AngularJS ?

Asked on December 10, 2018 in knockout js.
Add Comment


  • 2 Answer(s)

        Try this code for with binding :

    <h1>{{city}}</h1>
    <p ng-repeat="c in [coords.or.possibly.deeper.in.tree]">
        Latitude: {{c.latitude}},
        Longitude: {{c.longitude}}
    </p>
    
    Answered on December 10, 2018.
    Add Comment

        This solution supports expressions in koWith and also it watches for updating property/expression mentioned in koWith :

    .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.writable = 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);
               });
            }
        };
    });
    
    Answered on December 10, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.