【发布时间】:2016-07-18 14:14:01
【问题描述】:
这是对我的指令的简化:
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>
在我的控制器中,我有:
$scope.itemNameBuildFunction = function() {
return $scope.value1 + $scope.value2;
};
我希望我的指令在链接时(它位于 ng-if 子句内,因此,我的意思是,当 ng-if 条件评估为真时)调用 attrs.itemname() $scope 函数,分配控制器链接函数中的 scope.itemname 变量。
相反,我得到的是错误:
TypeError: attrs.itemname is not a function
你能给我一些指示吗?如您所见,我对角度指令感到很困惑... :-(
【问题讨论】:
-
您是否关闭了指令 并尝试了 scope.itemname = attrs.itemname;
-
这个函数
attrs.itemname()是什么?从来没有见过它定义...如果它被定义为函数 attrs 转换为 JSON 对象。所以你必须使用 angular.fromJson(attrs.itemname) -
@MandeepSingh:首先建议:谢谢,刚刚更正了我的答案;第二个建议:那样,在生成的表单中我得到字符串:
itemname,这不是我所期望的...... :-( -
@Zargold:
attrs.itemname包含一个字符串 (itemNameBuildFunction),它是一个 $scope 函数名... -
@MandeepSingh:不,不是:我得到了函数名称,而不是评估的函数结果... :-(
标签: javascript angularjs using-directives