问题
Whenever I use a directive within itself, the page freezes, and eats up more and more CPU and RAM until the tab hangs.
What I have is this
Application.Directives.directive('somed', function() {
return {
restrict: 'E',
// Load the template from a separate HTML file
templateUrl: 'directives/somed/view.html',
replace: true
};
});
and template like
<div ng-if="nonexistent">
<somed></somed>
</div>
Which should never load the nested directive (the ng-if evaluates to false, so no content is shown. This is confirmed if I put a div tag instead of somed). Yet, the browser hangs on it.
How come, and how can I prevent it?
回答1:
The documentation of ng-if says:
Also,
ngIf
recreates elements using their compiled state.
And since template for somed
references somed
, it'll not be able to successfully compile.
That will explain the problem.
There are several ways of preventing it, depending on your needs.
- You can include the
template
using an ng-include and putting the template in your $templateCache. - You can dynamically set the
html
of the element on which this directive is being called in thelink
function and then use the $compile service to interpret the (possibly recursive) directives inside it.
回答2:
Its like doing this:
var iAmAlwaysTrue = true;
function test(){
if(iAmAlwaysTrue)
test();
} // end test
test();
Like I said in my comment its not breaking AngularJS its just poor coding. If I did this in C++, is it breaking C++ or just bad code?
EDIT: If you were trying to prove that a recursive situation would exist, that AngularJS would identify the directive in the directive's own template then I'm guessing you succeeded given the outcome of your experiment, but its my guess that a test could have been avoided given that Angular's own directives ng-?
are interpreted in a directive's template just fine - there's no reason directive's you create wouldn't also be.
来源:https://stackoverflow.com/questions/19590314/nested-directives-break-angular