Angular:有选择地编译模板

dru*_*ple 7 javascript templates angularjs

我知道这ng-non-bindable允许给定元素及其子元素不被编译为模板.它似乎是根据需要在整个模板中添加的.有没有办法告诉Angular不处理给定的元素,但是"戳洞"并允许处理选定的子元素?例如,我希望能够做到这样的事情:

<div ng-non-bindable>
    <div>{{2+2}}</div>
    <div ng-bindable>{{2+2}}</div>
</div>
Run Code Online (Sandbox Code Playgroud)

并输出:

{{2 + 2}}

4

据我所知,即使它存在,ng-non-bindable也不会ng-bindable被允许处理.但是,是否存在任何允许像我所表达的模板方法的方法?

为了更加彻底,我的理想解决方案不会处理任何Angular,直到找到它ng-bindable,而不仅仅是花括号表达式.例如:

<div ng-non-bindable>
    <div ng-repeat="n in [1,2,3]">{{n+2}}</div>
    <div ng-bindable ng-repeat="n in [1,2,3]">{{n+2}}</div>
</div>
Run Code Online (Sandbox Code Playgroud)

会导致:

{{N + 2}}

3

4

dfs*_*fsq 4

自定义nonBindable指令

ngNonBindable由于指令的配置方式,您将无法像这样使用(好吧,您可以装饰它)。然而,使用这种行为编写自定义指令非常容易:

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);
                });    
            };
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

<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>
Run Code Online (Sandbox Code Playgroud)

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

装饰ngNonBindable

您可以ngNonBindable像这样装饰原始指令:

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;
    });
});
Run Code Online (Sandbox Code Playgroud)

并这样使用它:

<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>
Run Code Online (Sandbox Code Playgroud)

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