Michael
Michael

Reputation: 93

AngularJs - Delete all directives based on classname

I have been banging my head against my keyboard for a while.

I have a directive that dynamically gets data from the server. I hide show dropdown list based on subsequent dropdownlist value. I would like to remove all previous selection when I make a new selection. What I am experiencing is that data still remains from previous selection even after I clear down.

Please find below my code: function link(scope, element) { scope.displayChildren = displayChildren;

  function displayChildren() {
    var currentItem = scope.model;
    scope.children = [];
    var elementName = currentItem.name + '-child';
    var elementResult = angular.element(document.querySelector('.' + elementName));

    if ( elementResult.length > 0) {
      element.contents().remove();
      elementResult.contents().remove();
      element.append('<composed-components model="model"></composed-components>');
      $compile(element.contents())(scope);
    }

    for (var i = 0, x = currentItem.children.length; i < x; i++) {
      var currentChild = currentItem.children[i];
      var array = currentChild.parentValue.split(',');
      scope.children = getScopeChildren(array, currentChild);
    }
    if (scope.children.length < 1) return;
    element.append('<composed-components class="{{child.parentName}}-child" ng-repeat="child in children track by child._id" model="child"></composed-components>');
    $compile(element.contents())(scope);
  }

  function getScopeChildren(array, currentChild) {
    if (scope.model.currentValue === null) {
      return [];
    }
    if (array.length > 1) {
      for (var i = 0, x = array.length; i < x; i++) {
        scope.children = compare(scope.model.currentValue.value, array[i], scope.children, currentChild);
      }
    } else {
      scope.children = compare(scope.model.currentValue.value, currentChild.parentValue, scope.children, currentChild);
    }
    return scope.children;
  }

  function compare(value1, value2, array, currentValue) {
    if (value1 === value2) {
      array.push(currentValue);
    }
    return array;
  }
}

Any help will be greatly appreciated.

Upvotes: 3

Views: 47

Answers (1)

glcheetham
glcheetham

Reputation: 1003

If you're binding the data from the dropdowns to the scope with an ng-model attribute you can just delete the values from the scope and the values in the dropdowns will automatically update via angular's clever two-way data binding.

You may also want to check out the ngOptions directive for a quick way to abstract dropdown population logic away from the controller/directive link function.

Upvotes: 1

Related Questions