AngularJS 将属性中的 URL 传递给指令的隔离范围 - 意外标记“:”
AngularJS pass URL in attribute to isolated scope of directive - unexpected token ':'
我是AngularJS的新手,几天前才开始使用它,所以如果问题本身不正确,请原谅我。
我 运行 遇到的问题是我想通过属性将 URL 参数传递到我的指令的隔离范围,但是在 :
部分 http://
它给我一个错误,说 Syntax Error: Token ':' is an unexpected token at column 5 of the expression [http://
...
指令的 HTML 部分(我 "call" 的地方)是这样的:
<myDirective datasource="http://url"></myDirective>
然后我像这样将它绑定(?)到隔离范围:
scope: {
dataSource: '=datasource'
}
如果属性的值只包含简单字符,则可以。我该如何解决这个问题?
谢谢。
不要在指令中使用“=”,而是使用@,因为您传递的是普通字符串。
scope: {
dataSource: '@datasource'
}
如果您想进行双向数据绑定'='
,您必须将其与作用域变量绑定或传递带引号的字符串:
<myDirective datasource="'http://url'"></myDirective>
在您的案例中,angular 正在尝试评估 datasource
属性的值。因为你提到 =
即变量的双向绑定。
如果您将 URL 包裹在 '
(单引号)内将解决您的问题。因为提到的值将直接绑定到指令隔离范围变量。
标记
<my-directive datasource="'http://url'"></my-directive>
要定义隔离作用域,只需将“@”放入作用域定义中并在指令中使用属性名称。
.directive('ggThumbnail', function()
{
return {
restrict: 'E',
scope: {
thumbnailSrc: '@',
thumbnailWidth: '@',
thumbnailHeight: '@'
},
link: function(scope, element, attrs, ctrl)
{
ctrl.init(element);
attrs.$observe('thumbnailSrc', function()
{
if (attrs.thumbnailSrc)
{
ctrl.prepareImage();
}
});
}
};
});
Angular 尝试将您的值用作变量名。
来自 here:"The object hash is used to set up two-way binding (using '=') or one-way binding (using '@') between the parent scope and the isolate scope. There is also '&' to bind to parent scope expressions."
你应该使用:
scope: {
dataSource: '@datasource'
}
我是AngularJS的新手,几天前才开始使用它,所以如果问题本身不正确,请原谅我。
我 运行 遇到的问题是我想通过属性将 URL 参数传递到我的指令的隔离范围,但是在 :
部分 http://
它给我一个错误,说 Syntax Error: Token ':' is an unexpected token at column 5 of the expression [http://
...
指令的 HTML 部分(我 "call" 的地方)是这样的:
<myDirective datasource="http://url"></myDirective>
然后我像这样将它绑定(?)到隔离范围:
scope: {
dataSource: '=datasource'
}
如果属性的值只包含简单字符,则可以。我该如何解决这个问题?
谢谢。
不要在指令中使用“=”,而是使用@,因为您传递的是普通字符串。
scope: {
dataSource: '@datasource'
}
如果您想进行双向数据绑定'='
,您必须将其与作用域变量绑定或传递带引号的字符串:
<myDirective datasource="'http://url'"></myDirective>
在您的案例中,angular 正在尝试评估 datasource
属性的值。因为你提到 =
即变量的双向绑定。
如果您将 URL 包裹在 '
(单引号)内将解决您的问题。因为提到的值将直接绑定到指令隔离范围变量。
标记
<my-directive datasource="'http://url'"></my-directive>
要定义隔离作用域,只需将“@”放入作用域定义中并在指令中使用属性名称。
.directive('ggThumbnail', function()
{
return {
restrict: 'E',
scope: {
thumbnailSrc: '@',
thumbnailWidth: '@',
thumbnailHeight: '@'
},
link: function(scope, element, attrs, ctrl)
{
ctrl.init(element);
attrs.$observe('thumbnailSrc', function()
{
if (attrs.thumbnailSrc)
{
ctrl.prepareImage();
}
});
}
};
});
Angular 尝试将您的值用作变量名。
来自 here:"The object hash is used to set up two-way binding (using '=') or one-way binding (using '@') between the parent scope and the isolate scope. There is also '&' to bind to parent scope expressions."
你应该使用:
scope: {
dataSource: '@datasource'
}