Deleting after adding an element through the angular directive breaks the ng-model at the input [radio]

I created a custom directive for switching elements from the DOM. This is similar to ng-show, but with the actual manipulation of dom, not using styles. For reasons beyond the scope of this question, I cannot use ng-show.

angular.module('myApp')
    .directive('daKeep', [
        function () {
      function link($scope, element, attributes) {

            var cacheElement, insertionElement;

            // the TRUTHY expression to watch
            var expression = attributes.daKeep;

            function removeElement() {
              if (insertionElement === undefined) {
                insertionElement = element.prev();
                cacheElement = element;
                element.remove();
              }
            }

            function addElement() {
              if (insertionElement !== undefined) {
                insertionElement.after(cacheElement);
                insertionElement = undefined;
              }
            }

            if (!$scope.$eval(expression)) {
              removeElement();
            }

            // watch the expression in $scope context to see when it changes
            $scope.$watch(expression, function (newValue, oldValue) {
            // Ignore first-run values since we've
            // already defaulted the element state
            if (newValue === oldValue) {
              return;
            }

            // Show element
            if (newValue) {
              addElement();
            } else {
              removeElement();
            }
          });
        }

      // Return the directive configuration.
      return ({
        link: link,
        restrict: "A"
      });
        }
    ]);

It worked fine for my needs, but when I used it on the container element that housed some of the [radio] input buttons, the bindings for my radio buttons were broken when the element was added back.

Is there any way to fix my directive so that the bindings do not break?

Example here: plunker

+4
2

ng-if ? , ng-show, DOM.

  <div ng-if="keepRadioButtons">
    <input type="radio" ng-value="true" ng-model="selectedValue" />Yes
    <input type="radio" ng-value="false" ng-model="selectedValue" />No
  </div>
+2

, element.remove(), angular, jQuery jQLite .

ng-if , detach remove.

+1

Source: https://habr.com/ru/post/1532743/


All Articles