【问题标题】:$parse Syntax Error when binding Angular Expression to Directive Attribute将 Angular 表达式绑定到指令属性时出现 $parse 语法错误
【发布时间】:2018-08-01 17:19:19
【问题描述】:

无法使用指令在模板上绑定属性

我似乎无法使用指令在模板上绑定属性。任何帮助或建议都会很棒!

它给了我这个错误:

[$parse:syntax] 语法错误:令牌“{”在第 2 列的键无效 表达式 [{{$ctrl.CalendarOpen}}] 开始于 [{$ctrl.CalendarOpen}}]。

这是我的指令:

app.directive('datePickerDirective', [function () {
    return {
        restrict: 'AE',
        scope: {
          
        },
        template: `
            <input type="text" class="form-control"
                   uib-datepicker-popup="shortDate"
                   name="date" is-open="{{$ctrl.CalendarOpen}}"
                   ng-model="test" datepicker-options="dateOptions"
                   ng-required="true" close-text="Close" />`,
        controller: function() {
            var $ctrl = this;
            $ctrl.CalendarOpen = true
        },
        controllerAs: '$ctrl',
    }
}]);

【问题讨论】:

  • is-open 属性中删除双花括号{{,即is-open="$ctrlCalendarOpen"
  • @georgeawg 谢谢!它没有在 html 中显示 is-open="true" 很奇怪,但它正在工作。如果我添加一个 id="{{$ctrl.CalendarOpen}}",它不会给我那个错误。

标签: angularjs angularjs-directive angular-ui-bootstrap angular-ui-datepicker


【解决方案1】:

is-open 属性中删除双花括号{{

template: `
    <input type="text" class="form-control"
           uib-datepicker-popup="shortDate"
           ̶n̶a̶m̶e̶=̶"̶d̶a̶t̶e̶"̶ ̶i̶s̶-̶o̶p̶e̶n̶=̶"̶{̶{̶$̶c̶t̶r̶l̶.̶C̶a̶l̶e̶n̶d̶a̶r̶O̶p̶e̶n̶}̶}̶"̶
           name="date" is-open="$ctrl.CalendarOpen"
           ng-model="test" datepicker-options="dateOptions"
           ng-required="true" close-text="Close" />`,

uib-datepicker-popup 指令试图使用以{{ 开头的$parse ServiceAngular Expressions 来评估is-open 属性是非法的。

来自文档:

错误:$parse:syntax 语法错误

说明

在表达式中存在语法错误时发生。编译表达式时会引发这些错误。错误消息包含更精确的错误描述,包括表达式中发生错误的位置(列)。

要解决此问题,请详细了解AngularJS expressions,找出错误并修复表达式的语法。

— AngularJS Error Reference - $parse:syntax Error


如果我添加一个id="{{$ctrl.CalendarOpen}}",它不会给我那个错误

在这种情况下没有错误,因为没有解析id 属性的指令。 $interpolate 服务正在评估双卷曲 {{ 括号内的表达式,将其转换为文本并插入到 DOM 中。

当指令将属性解析为Angular Expression 时,将插值混合到该表达式中是不明智的。

来自文档:

为什么混合插值和表达式是不好的做法:

  • 它增加了标记的复杂性
  • 不能保证它适用于每个指令,因为插值本身就是一个指令。如果另一个指令在插值运行之前访问属性数据,它将获得原始插值标记而不是数据。
  • 它会影响性能,因为插值会在范围内添加另一个观察者。
  • 由于不推荐使用,我们不对此进行测试,对 AngularJS 核心的更改可能会破坏您的代码

— AngularJS Developer Guide - mixing interpolation and expressions is bad practice

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-10
    • 2012-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多