Angular: Selectively compile templates

后端 未结 1 1868
孤独总比滥情好
孤独总比滥情好 2021-01-12 08:26

I know that ng-non-bindable allows a given element and its children to be not compiled as a template. It seems it was designed to be peppered throughout a temp

相关标签:
1条回答
  • 2021-01-12 08:52

    Custom nonBindable directive

    You will not be able to use ngNonBindable (well, you could decorate it) like this due to how directive is configured. However it's pretty easy to write custom directive with this behavior:

    app.directive('nonBindable', function($compile) {
        return {
            terminal: true, 
            priority: 999,
            compile: function(tElement) {
                return function(scope) {
                    var bindable = tElement[0].querySelectorAll('[bindable]');
                    [].forEach.call(bindable, function(el) {
                        $compile(el)(scope);
                    });    
                };
            }
        };
    });
    

    and use it like this:

    <div non-bindable>
        <div>{{2+2}}</div>
        <div bindable>{{2+2}}</div>
    </div>
    
    <br><br>
    
    <div non-bindable>
        <div ng-repeat="n in [1,2,3]">{{n+2}}</div>
        <div bindable ng-repeat="n in [1,2,3]">{{n+2}}</div>
    </div>
    

    Demo: http://plnkr.co/edit/NEDP4WkBN4TlXdXKo8WI?p=preview

    Decorate ngNonBindable

    You can decorate original ngNonBindable directive like this:

    app.config(function($provide) {
        $provide.decorator('ngNonBindableDirective', function($delegate, $compile) {
            var directive = $delegate[0];
            directive.compile = function(tElement) {
                return function(scope) {
                    var bindable = tElement[0].querySelectorAll('[bindable]');
                    [].forEach.call(bindable, function(el) {
                        $compile(el)(scope);
                    });
                };
            };
            return $delegate;
        });
    });
    

    and use it this way:

    <div ng-non-bindable>
        <div>{{2+2}}</div>
        <div bindable>{{2+2}}</div>
    </div>
    
    <br><br>
    
    <div ng-non-bindable>
        <div ng-repeat="n in [1,2,3]">{{n+2}}</div>
        <div bindable ng-repeat="n in [1,2,3]">{{n+2}}</div>
    </div>
    

    Demo: http://plnkr.co/edit/HVczVkkQR88hC7191ep0?p=preview

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