Why ngIf has higher priority than {{ }} (interpolate)?

前端 未结 2 945
暗喜
暗喜 2021-01-06 01:45

What is the reasoning behind setting ngIf priority (600) higher than {{ }}(100)? Shouldn\'t it have a lower priority to allow {{ }} in

相关标签:
2条回答
  • 2021-01-06 02:15

    To understand why it's doing that, observe the console of this sample here, where the custom directive, similar to ngIf, sits this time at priority 0. The directive is meant to remove the element and, without waiting, to add it back. You'll see however an error which is caused by the attempt to set the attributes back onto what remained due to transclude: elementwhich, in this case and that of the ngIf, is just a marker for where the element has been, in the form of a comment.

    To avoid that from happening, ngIf terminates the process early by having a higher priority, terminal:true and by monitoring directly its expression grabbed straight from $tAttrs. Interpolation will execute, but this is done at a later stage, by calling the transclusion function the moment the ngIf expression turns true, on a clone of the original element, now under its control. The new element will show nice and dandy under the comment element.

    Here is the same sample but fixed. The error condition is avoided.

    0 讨论(0)
  • 2021-01-06 02:24

    ng-if expects its value to be an angular expression - under the hood it just makes use of $scope.$watch. Therefore, if you want to condition including content of ng-if on some variable defined on the scope (let say: scope.hide), you put ng-if="hide" in your mark-up. No double curly braces here.

    Now back to your question: it is true that ng-if has priority of 600, but $interpolate is angular's service - not a directive. As such $interpolate does not define priority. Where did you get 100 from?

    UPDATE

    You can always condition including content of ng-if on some function (let say scope.conditionFn) by putting in your mark-up: ng-if="conditionFn()".

    UPDATE 2

    I updated your PLNKR to make it working. The inconsistencies between ng-if and ng-hide in your plunker had nothing to do with priority of interpolation taking place in $compile.

    UPDATE 3

    It seems that you are right that order of interpolation plays a role here, but... I really do not see any good reason to interpolate inside of angular's expression. The reason why ng-if has relatively high priority is that it removes/adds transcluded content from/to DOM, whereas ng-hide just shows/hides the transcluded content. I think it is a pure coincidence that one directive seems to work and the other not. But if you do not use unnecessary, superfluous tricks, both do work as intended, what my plunker shows.

    0 讨论(0)
提交回复
热议问题