2

Here is demo: https://jimliu.github.io/angular-ui-tree/ but what about the situation when You delete all of the current nodes and You want to create the very first node?

So far I've got something like this:

<a href="" ng-click="createFirstChapterInput()"><span class="glyphicon glyphicon-circle-arrow-right"></span> New chapter</a>
<div class="row">
   <div class="col-lg-12">
       <div ui-tree id="tree-root">
          <ol ui-tree-nodes ng-model="chapters">
             <li ng-repeat="chapter in chapters" ui-tree-node ng-include="'nodes_renderer'"></li>
          </ol>
  </div>
</div>

The nodes_renderer is a template, taken exactly from the demo. It's too long to paste it here. Generally speaking - it shoud take this template and compile it in function.

Here is the createFirstChapterInput function:

    $scope.createFirstChapterInput = function() {
        $scope.chapter = {};
        Restangular.copy({route: Chapters.url}, $scope.chapter);

        $scope.chapter['name'] = null;

        var result = $('<li>' + $('#nodes_renderer').html() + '</li>');

        $('#tree-root').find('ol').prepend(result);

        $compile(result)($scope);
        result.find('input.new').focus();
    }

But well, it ends up on an error :

Controller 'uiTreeNode', required by directive 'uiTreeHandle', can't be found!

I don't know how to pass this controller to scope so compile would see it. Also I'm not sure whether the code is proper for this or is there any better solution.

mmmm
  • 3,768
  • 9
  • 36
  • 63

1 Answers1

1

You are running into issues because you are not "thinking in Angular". This SO question and answer is a good place to start.

In a nutshell, you don't reason in terms of DOM elements in Angular's controllers - instead, think of the model and create that.

You want to add the very first item - add it to the model chapters, and Angular would make the View reflect your model with how you bound it - in this case, with angular-ui-tree:

$scope.createFirstChapterInput = function() {
    var firstChapter = {name: "whatever"};
    $scope.chapters.push(firstChapter);
}
Community
  • 1
  • 1
New Dev
  • 48,427
  • 12
  • 87
  • 129
  • holly crap, You are totally right! But there are so minor issues, like for example - when I want to focus on input which is being created after I push new chapter to chapters array, then I think jQuery and it's way of thinking is necessary, isn't it? – mmmm Jan 31 '15 at 22:50
  • With focusing, yes - DOM manipulation is needed, but you should restrict that to directives, and there are some examples and questions online about auto-focusing. To save yourself from headaches, do NOT have anything related to DOM manipulations in the controllers. – New Dev Jan 31 '15 at 23:09