2013-10-29 102 views
2

後的HTML看起來像AngularJS指令適用於一個元素。如何嵌套NG重複完成

外指令的樣子:

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

沒有重複,按預期的方式應用外指令。但重複之後,在重複將適當的節點寫入DOM之前應用外部指令。

我見過在指令中使用超時的建議,這對我來說似乎有些破綻。此外,它看起來像有一個完成重複的鉤子,我可以用它來改變範圍並重新應用指令。

+0

This SO post would help you http://stackoverflow.com/questions/15207788/calling-a-function-when-ng-repeat-has-finished – Chandermani

+0

@Chandermani - 謝謝。我嘗試添加到內部指令:if(scope。$ last === true){$ timeout(function(){scope.finished = true;});},然後從外部指令中觀察。範圍發生變化,但觸發第一個元素而非最後一個元素。 –

+0

你不應該在你的子指令中做'scope.finished = true;'。這設置了本地範圍。您應該使用'$ scope。$ emit'來引發一個事件。 – Chandermani

回答

-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 
    } 
} 
}); 
+0

期望的行爲是內部指令首先寫入DOM,然後將外部指令應用於結果。 –

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="[email protected]" 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 - 謝謝你的推動!