是否可以在指令中创建私有函数?我需要在指令中执行一个相当复杂的过程来填充指令的模板.
像这样的东西(HTML):
<textarea the-result="data">
</textarea>
Run Code Online (Sandbox Code Playgroud)
使用Javascript:
angular
.module("MyModule")
.directive("theResult", [function () {
return {
scope: {
theResult: "="
// calculatestuff = function(d){ // ... } can't put it here (error)
},
template: ' ... '
+ '{{calculatestuff(theResult.someproperties)}}'
+ ' ... '
}
}])
Run Code Online (Sandbox Code Playgroud)
我在哪里可以放calculatestuff
?
Bla*_*ole 14
请注意,directive(directiveName, directiveFunction)
仅使用directiveFunction
返回的内容.您可以在此函数中执行任何操作,例如,定义其他函数:
angular
.module("MyModule")
.directive("theResult", [function () {
var calculateStuff = function (d) {
// ...
};
return {
// ...
}
}]);
Run Code Online (Sandbox Code Playgroud)
但是当然,calculateStuff
在$digest
循环期间不再存在并且没有链接到范围,因此您将无法在模板中调用它.如果这确实是您想要做的,请考虑在链接阶段将您的功能放在范围内:
angular
.module("MyModule")
.directive("theResult", [function () {
return {
scope: {
theResult: "="
},
template: ' ... '
+ '{{calculatestuff(theResult.someproperties)}}'
+ ' ... ',
link : function ($scope) {
$scope.calculateStuff = function (d) {
// ...
};
}
}
}]);
Run Code Online (Sandbox Code Playgroud)
由于您使用隔离范围,因此无法从指令外部访问此函数.
归档时间: |
|
查看次数: |
6044 次 |
最近记录: |