AngularJS([$ parse:syntax]语法错误:令牌':'是一个意外的令牌,当值为URL时

时间:2016-09-21 07:03:39

标签: javascript angularjs angularjs-directive

我已经创建了如下指令:

angular.module('mymodule')
.directive('httpsimg', function () {
    return {
        restrict: 'E', //E = element, A = attribute, C = class, M = comment         
             //@ reads the attribute value, = provides two-way binding, & works with functions
       scope: {
            style: '@',
            width: '=',
            height: '=',
            'src': '='
        },
       template: '<img src="{{src}}" width="{{width}}" height="{{height}}" style="{{style}}" />',
        link: function ($scope, element, attrs) {

                var srcparts = $scope.src.replace('http','https');
                $scope.src=srcparts;

        } //DOM manipulation
    }
});

然后我在我的Html代码中使用它,如下所示:

    <httpsimg src="http://www.mytest.com/imgdir/logo.png" width="50" />

如果在我的指令中将src更改为单向绑定(@),如下所示:

 scope: {
            style: '@',
            width: '=',
            height: '=',
            'src': '@'
        }

它工作正常,我的意思是我可以获得价值并且没有错误。但是,如果我改变@ to =以进行双向绑定,我会看到错误 另外我发现问题是因为Url因此如果我将网址更改为一个没有点和斜线的简单世界,它可以正常工作。

1 个答案:

答案 0 :(得分:2)

=双向绑定是绑定表达式,例如变量

<httpsimg src="foo">

foo是范围变量。 https://…肯定不是范围变量,并且是变量或表达式的无效语法。如果使用=绑定,则需要提供文字值作为表达式文字:

<httpsimg src="'http://www.mytest.com/imgdir/logo.png'">
               ^                                     ^

就像在Javascript中编写字符串文字一样。或许更好地说明一下:

<httpsimg src="'http://' + 'www.mytest.com/imgdir/logo.png'">

由于您没有绑定变量表达式,因此使用双向绑定没有意义。如果您只想传递一个文字值,那正是@的用途。

相关问题