将 Angular 表达式绑定到指令属性时出现 $parse 语法错误

$parse Syntax Error when binding Angular Expression to Directive Attribute

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

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

它给我这个错误:

[$parse:syntax] Syntax Error: Token '{' invalid key at column 2 of the expression [{{$ctrl.CalendarOpen}}] starting at [{$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 属性中删除双大括号 {{

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 Service and Angular Expressions 计算 is-open 属性是非法的。

来自文档:

Error: $parse:syntax Syntax Error

Description

Occurs when there is a syntax error in an expression. These errors are thrown while compiling the expression. The error message contains a more precise description of the error, including the location (column) in the expression where the error occurred.

To resolve, learn more about AngularJS expressions, identify the error and fix the expression's syntax.

— AngularJS Error Reference - $parse:syntax Error


If I add an id="{{$ctrl.CalendarOpen}}", it would not give me that error

在那种情况下没有错误,因为没有指令解析 id 属性。双 curley {{ 括号内的表达式正在由 $interpolate 服务求值,转换为文本,并插入到 DOM.

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

来自文档:

Why mixing interpolation and expressions is bad practice:

  • It increases the complexity of the markup
  • There is no guarantee that it works for every directive, because interpolation itself is a directive. If another directive accesses attribute data before interpolation has run, it will get the raw interpolation markup and not data.
  • It impacts performance, as interpolation adds another watcher to the scope.
  • Since this is not recommended usage, we do not test for this, and changes to AngularJS core may break your code

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