2016-09-21 49 views
0

我有一個樹結構,它有很多項目,所以它工作得很慢。我試圖用JavaScript重寫它以獲得更多的性能。但我被困在ng-click用ng-click在foreach循環中編譯html字符串

HTML:

<jstree initialstructure="vm.initialStructure" get-child-nodes="vm.getChildNodes()"></jstree> 

JS:

(function() { 
angular 
    .module('app.jstree') 
    .directive('jstree', Jstree); 

Jstree.$inject = ['$compile']; 

function Jstree($compile) { 
    var directive = { 
     restrict: 'E', 
     controller: 'JstreeController', 
     controllerAs: 'jst', 
     replace: true, 
     scope: { 
      initialstructure: '=', 
      getChildNodes: '&' 
     }, 
     link: function (scope, element, attrs) { 
       scope.$watch('initialstructure', function (items) { 
        if (items) { 
         var html = ""; 
         angular.forEach(items, function (item) { 
          html = html.concat('<li ui-tree-node>' + item.title); 
          var selectedNodeCls = item.selected ? 'selected-node' : ''; 
          html = html.concat('<div ui-tree-handle ng-click="alert(item);" class="' + selectedNodeCls + '" tooltip="' + item.title + '">'); 
          html = html.concat('</div>'); 
          html = html.concat('</li>'); 
         }); 
         element.html(html); 
         element = $compile(element)(scope); 
        } 
        scope.alert = function(item) { 
         console.log(item); //this is undefined, obviously because it is not on the scope 
        } 
       }); 
      } 
    }; 
    return directive; 
    } 
})(); 

怎麼會這樣來解決?

+0

你可以把更多的代碼。我試圖重現錯誤,並且我必須對你的代碼的外觀做出很多假設。 –

+0

@DarinCardin完成了,但這不是我第一次寫的東西。只是裏面的代碼指令。相關的問題是ng-click,技術是如何工作的 – bokkie

+0

您可以嘗試將替換的html重新綁定爲angular。看看:http://stackoverflow.com/questions/27131078/how-to-replace-a-html-content-with-jsf-rerender-or-ajax-load-and-rebind-the-new –

回答

0

我做了什麼,我不知道這是否是最乾淨的方式,自動取款機工作原理:

angular.forEach(items, function (item) { 
     ............ 
     html = html.concat('<div ui-tree-handle ng-click="alert(initialstructure[' + index + ']);" class="' + selectedNodeCls + '" tooltip="' + item.title + '">'); 
     .......... 
相關問題