如何在没有双大括号的情况下在模板中解析值
How to get values resolved in template without double curly brackets
我正在使用指令和模板。我的模板如下
<div>
<a data-my-dir="item" data-attr1="true"
data-attr2="{{itemParentId}}"
data-attr3="{{item.id}}">
</a>
</div>
这里由于添加了花括号手表,影响了我的表现。我不想要手表,因为我不打算修改 attr2 或 attr3。
我只想在这里直接解析值。
我们可以在不需要 watch 的地方使用 bindonce 指令,我们可以在其中使用 bo-text="xyz" 代替,但在这里我想将值作为 attr 传递给我的自定义指令。
在我的指令的 link 函数中,我将点击事件与元素绑定如下
link: function (scope, element, attrs) {
element.bind('click', function (event) {
var myAttr1 = attrs.attr1;
var myAttr2 = attrs.attr2;
}
}
因此,由于 attr1 和 attr2 模板中的那些手表,我在点击事件中解决了这些值。
有哪些替代方案?
您可以直接使用 data-attr2="itemParentId"
但为此您需要使用 =
因为当前您正在使用指令的 @
选项。
app.directive('myDir', function(){
return {
scope: {
dataAttr1: '=', //or '=dataAttr1'
dataAttr2: '=' //or '=dataAttr2'
},
link: function(scope, element, attrs){
console.log(scope.dataAttr1);
console.log(scope.dataAttr2);
}
}
})
一次性绑定
似乎是 one time binding 的一个很好的用例(如果您使用的是 angular 1.3+)
<div>
<a data-my-dir="item"
data-attr1="true"
data-attr2="{{::itemParentId}}"
data-attr3="{{::item.id}}">
</a>
</div>
该指令看起来像
angular.module('app', [])
.directive("myDir", function() {
return {
restrict: "A",
scope: {
"attr1": "@",
"attr2": "@",
"attr3": "@",
},
template: '<span> {{attr1}} {{attr2}} {{attr3}}</span>'
};
})
演示
http://plnkr.co/edit/GJCZmb9CTknZZbcRHN7s?p=preview
我正在使用指令和模板。我的模板如下
<div>
<a data-my-dir="item" data-attr1="true"
data-attr2="{{itemParentId}}"
data-attr3="{{item.id}}">
</a>
</div>
这里由于添加了花括号手表,影响了我的表现。我不想要手表,因为我不打算修改 attr2 或 attr3。 我只想在这里直接解析值。
我们可以在不需要 watch 的地方使用 bindonce 指令,我们可以在其中使用 bo-text="xyz" 代替,但在这里我想将值作为 attr 传递给我的自定义指令。
在我的指令的 link 函数中,我将点击事件与元素绑定如下
link: function (scope, element, attrs) {
element.bind('click', function (event) {
var myAttr1 = attrs.attr1;
var myAttr2 = attrs.attr2;
}
}
因此,由于 attr1 和 attr2 模板中的那些手表,我在点击事件中解决了这些值。
有哪些替代方案?
您可以直接使用 data-attr2="itemParentId"
但为此您需要使用 =
因为当前您正在使用指令的 @
选项。
app.directive('myDir', function(){
return {
scope: {
dataAttr1: '=', //or '=dataAttr1'
dataAttr2: '=' //or '=dataAttr2'
},
link: function(scope, element, attrs){
console.log(scope.dataAttr1);
console.log(scope.dataAttr2);
}
}
})
一次性绑定
似乎是 one time binding 的一个很好的用例(如果您使用的是 angular 1.3+)
<div>
<a data-my-dir="item"
data-attr1="true"
data-attr2="{{::itemParentId}}"
data-attr3="{{::item.id}}">
</a>
</div>
该指令看起来像
angular.module('app', [])
.directive("myDir", function() {
return {
restrict: "A",
scope: {
"attr1": "@",
"attr2": "@",
"attr3": "@",
},
template: '<span> {{attr1}} {{attr2}} {{attr3}}</span>'
};
})