【发布时间】:2016-02-10 08:07:53
【问题描述】:
我有一个关于值在指令中的工作方式的问题。我有一个指令,它有一个模板,在同一个模板中,我想调用一个(全局定义的)javascript 函数,并且我想将我从 directive 获得的值传递到该 javascript 函数中(它可能听起来有点混乱)。 这是示例代码。
angular.module("Shell").directive("myFormField", function () {
return {
scope: {
text: "@",
required: "@",
},
transclude: true,
replace: true,
template:
'<div>' +
'<label style="white-space: nowrap;font-weight: normal;width: 100% !important">'+globalLoadText(text)+
'<div style="margin-top: 1.5px;" ng-transclude />' +
'</label>' +
'</div>'
};
});
globalLoadText() 是我在 angular 外部定义的全局方法(在根范围内的普通 js 文件中)text 将是我想从指令中获取的值。
我希望我已经清楚地写下了我的问题。任何帮助将不胜感激。谢谢!!
【问题讨论】:
-
在我们赋予你做一些听起来很臭的事情之前,你能解释一下为什么你必须使用全局函数吗?
-
为什么要尝试跳出 AngularJS 生态系统?如果你有一个全局函数,创建一个服务来在指令、控制器等之间共享函数。这样它是模块化的并且保持在 AngularJS 的摘要周期内。
-
我认为问题是,您的函数将首先评估,而
text范围内不存在。使用过滤器而不是函数会起作用吗?所以你可以做{{text | globalLoadText}}? docs.angularjs.org/api/ng/filter/filter
标签: javascript angularjs angularjs-directive angularjs-templates