angular-ui-tree: как получить HTML-элемент последнего добавленного узла
Может быть, это глупый вопрос, но я не нашел решения здесь в stackru или в документации angular-ui-tree.
Мне нужно получить элемент HTML последнего добавленного узла.
Чтобы быть более точным, у меня есть xeditable элемент в шаблоне узла, который мне нужно показать и сфокусировать при создании нового узла.
Как мне это сделать.
Спасибо за вашу помощь.
1 ответ
Решение
Я не проверял, но я думаю, что это должно сделать это:
[ШАГ 1] В вашем контроллере:
// Dummy data (please mind the IDs)
$scope.data = [{
'id': 1,
'title': 'node 1',
'type': 'parent', // I like to flag them as well
'nodes': [{
'id' : 11,
'title' : 'node 1.1',
'type': 'child'
}]
}];
// This will add the new item into your stack
$scope.newMenuItem = function() {
$scope.data.push({
id: $scope.data.length + 1,
title: 'test ' + ($scope.data.length + 1),
type: 'parent',
nodes: []
});
// You just pushed the new item into your tree, now we have to somehow reference it
// within our DOM (getting the HTML version of it)
// Please see STEP 2 before reading here - come back once you did that
// ---------------------------------------------------------------------
// Now get the newest element from our tree and convert it to an angular element
var lastItem = $scope.data[$scope.data.length - 1];
// Convert to an angular element (added timeout so we can catch the newly rendered item onto DOM - if no timeout, you can't query the item)
var t = setTimeout(function() {
console.log(angular.element(document.querySelector('#menu-item-' + lastItem['id'])));
clearTimeout(t);
}, 150);
};
[ШАГ 2] В вашем HTML
<div ng-controller="DummyController">
<div ui-tree>
<button ng-click="newMenuItem()">Add new item</button>
<ul class="menu" ui-tree-nodes ng-model="data">
<!-- As you can see, I've put the item's ID so I can reference it back into my controller -->
<!-- Now go back to your controller and see how you do that -->
<li ng-repeat="item in data" ui-tree-node data-type="{{item.type}}" id="menu-item-{{item.id}}">
<a href="#">{{item.title}}</a>
</li>
</ul>
</div>
</div>