2013-04-23 67 views
0

我使用ng-repeat實例化了一個小部件。初始創建工作正常,但之後停止更新。下面是index.html的摘錄:當使用ng-repeat時刪除列表項時未被刪除的Transcluded元素

<div> 
    <x-node ng-repeat="node in nodes"></x-node> 
</div> 

諧音/ node.html:

<div>{{node.name}}</div> 

而且指令:

angular.module('directive', []).directive('node', function() { 
    return { 
     restrict: 'E', 
     scope: true, 
     templateUrl: 'partials/node.html', 
     replace: true, 
     compile: function(tElement, tAttrs, transclude) { 
      return { 
       post: function(scope, iElement, iAttrs) { 
        scope.$on('$destroy', function(event) { 
         console.log('destroying'); 
        }); 
       } 
      }; 
     } 
    }; 
}); 

如果我修改這樣的控制檯節點列表:

var e = angular.element($0); 
var s = e.scope(); 
s.nodes.splice(1,1); 
s.$apply() 

...然後$destroy回調運行,但渲染的元素不會改變。我的指令中有什麼遺漏嗎?

演示:Plunker

+3

不應該'template'是'templateUrl'? – 2013-04-23 03:48:20

+0

@JosephSilber啊是的,的確如此。謝謝,我在問題中解決了這個問題。 – z0r 2013-04-23 03:55:31

+0

@阿倫,感謝Plunker的演示!我注意到如果模板被包含在指令中而沒有使用templateUrl,它似乎可以工作... – z0r 2013-04-23 04:40:45

回答

1

看來這確實是一個錯誤,這是固定在1.2系列AngularJS的。 Here's an updated demo使用1.2。

的index.html:

<!DOCTYPE html> 
<html ng-app="my-app"> 

    <head lang="en"> 
    <meta charset="utf-8"> 
    <title>Custom Plunker</title> 

    <link rel="stylesheet" href="style.css"> 

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script> 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js"></script> 

    <script src="app.js"></script> 
    </head> 

    <body ng-controller="AppController"> 

    <div id="ct"> 
     <x-node ng-repeat="node in nodes"></x-node> 
    </div> 

    <button id="test">Remove element [1]</button> 
    </body> 

</html> 

app.js:

var app = angular.module('my-app', [], function() { 

}) 

app.controller('AppController', function ($scope) { 

     $scope.nodes = [{ 
      name: 'one' 
     }, { 
      name: 'two' 
     }, { 
      name: 'three' 
     }]; 


}) 

app.directive('node', function() { 
    return { 
     restrict: 'E', 
     scope: true, 
     templateUrl: 'node.html', 
     replace: true, 
     compile: function(tElement, tAttrs, transclude) { 
      return { 
       post: function(scope, iElement, iAttrs) { 
        scope.$on('$destroy', function(event) { 
         console.log('destroying'); 
        }); 
       } 
      }; 
     } 
    }; 
}); 

$(function(){ 
    $('#test').click(function(){ 
    var el = $('#ct').children().first(); 
    if(el.length){ 
     var e = angular.element(el[0]); 
     var s = e.scope(); 
     s.nodes.splice(1,1); 
     s.$apply() 
    } 
    }) 
}); 

node.html:

<div>{{node.name}}</div>