web-dev-qa-db-ja.com

構文エラー:ディレクティブに変数を渡す場合、トークン「:」は予期しないトークンです

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 )
            })
        }
    }
}])
12
Noah

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に注目してください。

3
adam0101