Transcluded element not being deleted on removal o

2019-08-20 23:25发布

I have a widget that I'm instantiating using ng-repeat. Initial creation works fine, but after that it stops updating. Here's an excerpt from index.html:

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

partials/node.html:

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

And the directive:

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');
                    });
                }
            };
        }
    };
});

If I modify the list of nodes in the console like this:

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

... then the $destroy callback runs, but the rendered elements do not change. Is there something I'm missing from my directive?

Demo: Plunker

1条回答
Ridiculous、
2楼-- · 2019-08-20 23:43

It seems this was indeed a bug, which is fixed in the 1.2 series of AngularJS. Here's an updated demo that uses 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>
查看更多
登录 后发表回答