属性插值 (AngularJS)



我想允许用户在应用程序中编辑表单,例如设置字段的标签,但我希望用户享受Angular插值的力量来创建动态表单。

当涉及到标签时,这很容易,有服装指令

但是当涉及到属性时,这更加困难。假设我想让用户为一个问题设置一个相关性方程,例如 movieRating.relevant='{{seenMovie===true}}' .

我目前通过在插值变量上调用插值来解决这个问题。

模板:

<div class="control-group" ng-show="interpolate('{{ movieRating.relevant }}')">
    <!--  field html -->
</div>

指令/控制器:

scope.interpolate = function(text, mustHaveExpression, trustedContext) {
    $interpolate(text, mustHaveExpression, trustedContext)(scope)
}

我正在寻找一种更 Angular 的方式来做到这一点(例如,可以使用 $compile 的方法)。

创建一个 Angular 滤波器,为您执行插值,并且可以在任何地方重复使用:

angular
  .module(...)
  .filter(
    'interpolate',
    ['$parse', $parse => (name, scope) => $parse(name)(scope)]
  );

。然后在模板中使用它:

<div ng-show="movieRating.relevant | interpolate:this">

瞧!

最好的方法是按照ccjmne的建议在其上使用管道

<div ng-show="movieRating.relevant | interpolate:this">

我在以下示例中详细介绍了代码不要忘记在@NgModule中导出和声明管道

目录

<a [href]="this.$urlProjectDetails | interpolate:this" target="_blank">

自定义管道

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'interpolate' })
export class InterpolatePipe implements PipeTransform {
// {{ context.url | interpolate:this}}
transform(
    text    : string,
    scope   : object,
    props   : object = {} // OverWrite this
): string {
    return this.interpolate(
        text,
        scope,
        props
    )
  }

      interpolate(stringToInterpolate : string, scope : object, props : object = null) {
        var LOCAL = {
            oSource : scope,// should be = this
            value : null,
            foundValue  : true
        }
        return stringToInterpolate.replace(/${(.*?)}/g, function(match, expr : string) {
            //try props for the value
            LOCAL.value = props || {};
            expr.split('.').some( currentExpr=>{
                if(currentExpr in LOCAL.value){
                    LOCAL.value = LOCAL.value[currentExpr];
                    return false;
                } else {
                    LOCAL.foundValue = false;
                    LOCAL.value = '';
                    return true;// stop execution of array with some()
                }
            })
            //if we did not found a value in the given props, find it in the this scope
            if(!LOCAL.foundValue){
                LOCAL.value = LOCAL.oSource
                expr.split('.').some( currentExpr=>{
                    if(currentExpr in LOCAL.value){
                        LOCAL.value = LOCAL.value[currentExpr];
                        return false;
                    } else {
                        LOCAL.foundValue = false;
                        LOCAL.value = '';
                        return true;// stop execution of array with some()
                    }
                })
            }
            return LOCAL.value
        });
    };
}

最新更新