Syntax Error: Token ':' is an unexpected token when passing variable to directive

Syntax Error: Token ':' is an unexpected token when passing variable to directive

我有一个名为 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: '='

来自 url: '@'

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

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

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.