gpt4 book ai didi

javascript - Angular : function call as attribute value for directive

转载 作者:行者123 更新时间:2023-12-02 14:24:01 25 4
gpt4 key购买 nike

这是我的指令的减少:

app.directive('myDirective', function() {
return {
restrict: 'E',
replace: true,
template:
'<form name="form" action="{{action}}" method="post" target="_blank">' +
'<input type="hidden" name="item_name" value="{{itemname}}">' +
'</form>',
scope: {
action: '@action',
itemname: '@itemname',
},
link: function(scope, element, attrs) {
scope.action = attrs.action || 'http://www.example.com';
scope.itemname = attrs.itemname();
}
};
});

我这样使用它:

<div ng-if="itemWasSelected">
<my-directive
action="{{ 'http://www.example.com' }}"
itemname="itemNameBuildFunction"
/>
</div>

在我的 Controller 中,我有:

$scope.itemNameBuildFunction = function() {
return $scope.value1 + $scope.value2;
};

我希望我的指令在链接时(它位于 ng-if 子句中,所以,我的意思是,当 ng-if 条件评估为 true 时)调用 attrs.itemname() $scope 函数,在 Controller 的链接函数中分配scope.itemname 变量。

相反,我得到的是错误:

TypeError: attrs.itemname is not a function

你能给我一些指示吗?正如你所看到的,我对 Angular Directive(指令)感到非常困惑......:-(

最佳答案

您不需要此语句 attrs.itemname()

传入指令的函数引用绑定(bind)到 scope 上的变量 itemname,该变量作为 link 函数中的第一个参数传递,其中 隔离范围

只需将语句更改为

scope.itemname = attrs.itemname();

致:

scope.itemname();  // this will call the function `itemNameBuildFunction`

编辑:

您已经在绑定(bind)函数中使用了@运算符,该运算符用于传递原语或对象的情况。您正在传递函数,因此,您应该使用&运算符,将计算作为函数。

scope: {
action: '@action',
itemname: '&itemname',
}

编辑2:您应该传递函数 itemNameBuildFunction() 而不是 itemNameBuildFunction

<my-directive action="{{ 'http://www.example.com' }}" 
itemname="itemNameBuildFunction()" />

工作中Plunker

关于javascript - Angular : function call as attribute value for directive,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38438987/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com