【问题标题】:Syntax Error: Token ':' is an unexpected token when passing variable to directive语法错误:将变量传递给指令时,令牌“:”是一个意外的令牌
【发布时间】:2015-04-17 04:36:01
【问题描述】:

我有一个名为 iframely 的指令,它位于 ng-repeat 中,如下所示:

<iframely url="iterator.url"></iframely>

这只是将值视为字符串"iterator.url",而不是实际的.url 值。为了进行实验,我直接输入了一个 URL:

<iframely url="https://soundcloud.com/braxe1/braxe-one-more-chance"></iframely>

这给了我Syntax Error: Token ':' is an unexpected token 错误。我最接近将此值传递给指令的是:

<iframely url="'{{iterator.url}}'"></iframely> // note double and single quotes

这会解析 iterator 的 URL 参数,但也会将其与 ' ' 单引号一起作为字符串的一部分传递。


编辑:也试过不带单引号。

<iframely url="{{iterator.url}}"></iframely>

得到Error: [$parse:syntax] Syntax Error: Token '{' invalid key at column 2 of the expression [{{iterator.url}}] starting at [{iterator.url}}]

这样做的正确方法是什么?


EDIT2:这是指令的代码:

angular.module( 'iframely', [])

.directive( 'iframely', [ '$http', '$sce', function ( $http, $sce ) {
    return {
        replace: true,
        restrict: "E",
        scope: {
            url: '='
        },
        template: '<div ng-bind-html="content"></div>',
        link: function ( scope, element, attrs ) {
            $http( {
                url: 'http://localhost:8061/iframely',
                method: 'GET',
                params: {
                    url: attrs.url
                }
            })
            .then( function ( result ) {
                scope.content = $sce.trustAsHtml( result.data.html )
            })
        }
    }
}])

【问题讨论】:

  • url="{{iterator.url}}" 不带单引号...
  • @micronyks 实际上,这是我尝试的第一个。 Error: [$parse:syntax] Syntax Error: Token '{' invalid key at column 2 of the expression [{{iterator.url}}] starting at [{iterator.url}}]
  • 你能贴出你的指令代码吗?
  • @adam0101 在上面添加。
  • 尝试将url: '=' 更改为url: '@',然后使用不带引号的大括号。

标签: angularjs angular-directive


【解决方案1】:

你必须替换url: '='

url: '@'

https://docs.angularjs.org/api/ng/service/$compile

【讨论】:

    【解决方案2】:

    将您的指令更改为以下内容:

    angular.module( 'iframely', [])
    
    .directive( 'iframely', [ '$http', '$sce', function ( $http, $sce ) {
        return {
            replace: true,
            restrict: "E",
            scope: {
                url: '@'
            },
            template: '<div ng-bind-html="content"></div>',
            link: function ( scope, element, attrs ) {
                $http( {
                    url: 'http://localhost:8061/iframely',
                    method: 'GET',
                    params: {
                        url: scope.url
                    }
                })
                .then( function ( result ) {
                    scope.content = $sce.trustAsHtml( result.data.html )
                })
            }
        }
    }])
    

    注意范围中的“@”和url: scope.url

    【讨论】:

      猜你喜欢
      • 2017-12-15
      • 2019-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-31
      • 1970-01-01
      • 1970-01-01
      • 2019-10-28
      相关资源
      最近更新 更多