2

html 看起来像:

<div ng-controller="MainCtrl">
    <outer>
      <inner ng-repeat="d in data">
        <div>{{d}}</div>
      </inner>
    </outer>
</div>

重复工作,内部指令按预期应用。

外部指令如下所示:

directives.directive('outer', function () {
    return {
        compile: function (elm) {
           // ... do some jQuery
        }
    }
});

如果没有重复,则按预期应用外部指令。但是对于repeat,在repeat 将适当的节点写入DOM 之前应用了outer-directive。

我已经看到在指令中使用超时的建议,这对我来说似乎有点骇人听闻。此外,看起来有一个完成重复的钩子,我可以使用它来更改范围并重新应用指令。

4

2 回答 2

0

这是我解决它的方法:

HTML:

<!doctype html>
<html ng-app="myApp">

<head>
  <meta charset="utf-8">
  <title>AngularJS Plunker</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <link rel="stylesheet" href="style.css">
  <script data-require="angular.js@1.0.x" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.js"></script>
  <script src="app.js"></script>
</head>
<body>

  <div ng-controller="MainCtrl">
    <outer>
      <inner ng-repeat="d in data">
        <div>{{d}}</div>
      </inner>
    </outer>
  </div>
</body>

</html>

应用程序.js:

var myApp = angular.module('myApp', ['myApp.directives']);

myApp.controller('MainCtrl', function($scope) {
  $scope.data = [1, 2, 3];
});

var directives = angular.module('myApp.directives', []);

directives.directive('inner', function() {

  return {
        restrict: 'E',
        scope: true,
        link: function(scope, element, attrs) {
            element.append("<div>Processing inner element.</div>");
            if (scope.$last) {
              element.append("Processed last inner element.");
              scope.$emit('foo', "");
            }
        }
  }      
});

directives.directive('outer', function() {
  return {
        restrict: 'E',
        scope: true,
        link: function(scope, element, attrs) {
            scope.$on('foo', function() {
              element.append("<div>Finished outer processing.</div>");
              element.append(element.getChildren());
              // this is critical if jQuery altered DOM in inner directive
              scope.$apply();
            });
        }
  }      
});

输出:

1
Processing inner element.
2
Processing inner element.
3
Processing inner element.
Processed last inner element.
Finished outer processing.

Plunker:http ://plnkr.co/edit/tMXq7fFeNLnDbn9ORdUS

@Chandermani - 感谢您的推动!

于 2013-10-31T03:56:33.273 回答
-1

我的建议是处理指令模板中的重复。

directives.directive('outer-directive', function () {
return {
    template:"<div ng-repeat='d in data'>"
                 + "<innerDirective id={{d.id}} text={{d.text}} />"
              +"</div>",
    controller: function ($scope, $element, $attrs){
           $scope.data = getData();
    }
    compile: function (elm) {
       // ... do some jQuery
    }
}
});
于 2013-10-29T04:04:32.343 回答