如何在嵌套的ng-repeat完成后将AngularJS指令应用于元素

时间:2013-10-29 03:52:02

标签: angularjs angularjs-directive angularjs-scope

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,在重复将相应的节点写入DOM之前应用outer-directive。

我已经看到了在指令中使用超时的建议,这对我来说似乎有些苛刻。另外,看起来有一个完成重复钩子,我可以使用它来改变范围并重新应用指令。

2 个答案:

答案 0 :(得分: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>

App.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 - 感谢你的轻推!

答案 1 :(得分:-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
    }
}
});