无法在指令控制器中设置变量

时间:2016-11-15 21:57:02

标签: javascript angularjs directive

我创建了一个指令:



<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>'
		}
	}]);
&#13;
&#13;
&#13;

第一次单击该对象时,它应该加载所有子项。每次后续点击都会切换列表的可见状态。这应该由vm.hasChildren变量控制。但是,每当我单击该对象时,vm.hasChildren都是未定义的。我可以设置这个变量,以便在重新加载页面之前保持其值吗?

1 个答案:

答案 0 :(得分:0)

再一次,答案是,&#34;我是个白痴。&#34;我在错误的位置检查hasChildren。当然在init中,hasChildren总是假的。请忽略这个愚蠢的问题。