angularjs – 在指令中创建私有函数
发布时间:2020-12-17 09:41:54 所属栏目:安全 来源:网络整理
导读:是否可以在指令内创建一个私有函数?我需要在一个指令中做一个相当复杂的过程来填充指令的模板. 这样的东西(HTML): textarea the-result="data"/textarea 使用Javascript: angular.module("MyModule").directive("theResult",[function () { return { scop
是否可以在指令内创建一个私有函数?我需要在一个指令中做一个相当复杂的过程来填充指令的模板.
这样的东西(HTML): <textarea the-result="data"> </textarea> 使用Javascript: angular .module("MyModule") .directive("theResult",[function () { return { scope: { theResult: "=" // calculatestuff = function(d){ // ... } can't put it here (error) },template: ' ... ' + '{{calculatestuff(theResult.someproperties)}}' + ' ... ' } }]) 我可以在哪里放钙?
请注意,directive(directiveName,directiveFunction)仅使用directiveFunction返回.你可以做任何你想要的内部的这个功能,例如,定义其他功能:
angular .module("MyModule") .directive("theResult",[function () { var calculateStuff = function (d) { // ... }; return { // ... } }]); 但是当然,在$digest循环中,calculateStuff不再存在,并且没有链接到作用域,所以你将无法在模板中调用它.如果这真的是你想要做的,那么考虑在连接阶段将你的功能放在范围内: angular .module("MyModule") .directive("theResult",[function () { return { scope: { theResult: "=" },template: ' ... ' + '{{calculatestuff(theResult.someproperties)}}' + ' ... ',link : function ($scope) { $scope.calculateStuff = function (d) { // ... }; } } }]); 由于您使用隔离的作用域,该函数将不能从指令外部访问. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |