0

I have created a directive as:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
.directive('treeView', ['treeViewService', 'passClickService', '$compile',  function (treeViewService, passClickService, $compile) {

  var controller = function () {
   var vm = this;

   vm.init = function (scope, element) {
    vm.element = element;
    vm.scope = scope;
    passClickService.register(vm.onClick);
    if (!vm.parentId) {
     var obj = angular.element($compile('<tree-branch ssc-id="{{vm.sscId}}" parent-id="{{vm.sscId}}" no-edit="{{vm.noEdit}}" can-delete="{{vm.canDelete}}"></tree-branch>')(vm.scope));
     vm.element.append(obj);
    } else {
     if (!vm.hasChildren) {
      vm.hasChildren = true;
      var myget = treeViewService.getChildren(vm.sscId);
      myget.then(function (data) {
       var objData = data.data || data;
       vm.children = objData.$values || objData;
       var obj = angular.element($compile('<tree-branch ng-repeat="child in vm.children" ssc-id="{{child}}" parent-id="{{vm.sscId}}"></tree-branch>')(vm.scope));
       vm.element.append(obj);
      });
     } else {
      element.toggle();
     }
    }
   }
  }

  var link = function (scope, element, attrs, vm) {
   var hasChildren = false;
   vm.init(scope, element);
  }
  return {
   restrict: 'E',
   scope: {
    sscId: '@',
    parentId: '@',
    noEdit: '@',
    noDelete: '@',
   },
   controller: controller,
   controllerAs: 'vm',
   bindToController: true,
   replace: true,
   transclude: true,
   link: link,
   template: '<ul class="nav nav-list tree" style="margin-left:10px" id="tree{{vm.sscId}}"></ul>'
  }
 }]);

The first time I click the object, it should load all children. Every subsequent click will toggle the visible state of the list. This should be controlled by the vm.hasChildren variable. However, Whenever I click the object, vm.hasChildren is undefined. HOw can I set this variable so that it keeps its value until the page is reloaded?

DrewB
  • 1,503
  • 1
  • 14
  • 28
  • In your init function you have used vm.hasChildren, but you have not declared that yet. You should have logic to set its correct value during init. If I am not missing something here – PM. Nov 15 '16 at 22:04
  • I added vm.hasChildren = false as the first line of init and now it's always false. – DrewB Nov 15 '16 at 22:09
  • oh, my bad. I missed the point that you want to change it on every click. So your init will be called only once, not on every click. The check of that hasChildren and action based on that should not be the part of init. You will have to move it to another function, which will get called on every click. – PM. Nov 15 '16 at 22:11

1 Answers1

0

Once again, the answer is, "I'm an idiot." I'm checking for hasChildren in the wrong spot. Of course in init hasChildren will always be false. Please disregard this moronic question.

DrewB
  • 1,503
  • 1
  • 14
  • 28