这里是 Plunker 中使用 Angularjs 指令的 TreeView 示例.
部分代码:
.directive('treeView', ['$compile', function($compile) {
return {
restrict: 'E',
scope: {
value: '=',
key: '=',
filter: '=',
idx: '='
},
link: function(scope, element, attrs) {
var value = scope.value
scope.curValue = scope.value;
console.log(scope.curValue)
var template =
'<ul>' +
'<li>{{key}}</li>' +
'<li class="inner-node" ng-repeat="(k,v) in curValue">' +
'<i class="collapsed" ng-show="haschildren(v)" ng-class="{\'list-plus\':!k' + "open" + '}" ng-click="k' + "open" + '=!k' + "open" + '"></i>' +
'<span class="" ng-click="seeAll(k)">{{k}}</span>' +
'</li>' +
'</ul>';
scope.haschildren = function(obj) {
return !$.isEmptyObject(obj)
};
scope.seeAll = function(key) {};
element.html('').append($compile(template)(scope));
}
};
}]);
我想通过单击切换按钮来更改树节点,该按钮将scope.fields设置为新值。
但是点击后没有任何变化。 我认为这是因为我以错误的方式使用了链接方法,但我不知道正确的方法是什么。
我应该做什么?
最佳答案
问题在于,当指令首次链接时,链接函数只执行一次。
您应该使用指令的 template 属性来设置模板。之后,您可以将scope.hasChildren和scope.seeAll方法放入该指令的 Controller 中。
检查更新的plunkr .
.directive('treeView', ['$compile', function($compile) {
return {
restrict: 'E',
scope: {
value: '=',
key: '=',
filter: '=',
idx: '='
},
template: '<ul>' +
'<li>{{key}}</li>' +
'<li class="inner-node" ng-repeat="(k,v) in value">' +
'<i class="collapsed" ng-show="haschildren(v)" ng-class="{\'list-plus\':!k' + "open" + '}" ng-click="k' + "open" + '=!k' + "open" + '"></i>' +
'<span class="" ng-click="seeAll(k)">{{k}}</span>' +
'</li>' +
'</ul>',
link: function(scope, element, attrs) {
},
controller: function($scope){
$scope.haschildren = function(obj) {
return !$.isEmptyObject(obj)
};
$scope.seeAll = function(key) {};
}
};
}]);
关于javascript - 使用 Angularjs 指令时如何刷新树的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30709356/