在Angularjs模板中绑定javascript方法
发布时间:2020-12-17 06:47:44 所属栏目:安全 来源:网络整理
导读:我的应用程序在客户端使用 Angularjs.我有五个使用相同逻辑的指令.以下是我的代码的必填详情 我有一个纯javascript类作为AppUtilities.js定义了以下方法 var AppUtilities = { //Get the guid for given collection getGUID: function (collectionName) { va
我的应用程序在客户端使用
Angularjs.我有五个使用相同逻辑的指令.以下是我的代码的必填详情
>我有一个纯javascript类作为AppUtilities.js定义了以下方法 var AppUtilities = { //Get the guid for given collection getGUID: function (collectionName) { var prefix; var guid; //get first two character if (!Utilities.isEmpty(collectionName)) { prefix = collectionName.substring(0,2); //Get timestamp var timestamp = Utilities.getTimestampId(); //concate prefix to get the guid guid = prefix + timestamp; } return guid; } }; >我有五个不同的指令,我需要使用“getGUID()”方法与模板绑定.由于模板只能与范围函数绑定,因此我在所有这五个模板中定义了范围方法,如下所示 scope.getGUID = function (collectionName) { return AppUtilities.getGUID(collectionName); } >然后在所有五个指令模板中,此方法作为范围变量绑定 <h4 class="guid" id="guid" data-ng-bind-template="{{getGUID('goal')}}"></h4> 如何避免将这些方法声明为范围变量并直接在HTML模板中用作AppUtilities.getGUID(collectionName)? 解决方法
有多种方式,但老实说,它似乎比它的价值更多的努力,因为你可以这样做:
scope.getGUID = AppUtilities.getGUID; 当然,你可以使用$rootScope,但对我个人来说感觉不对 – 我喜欢当事情被明确宣布并且不会神奇地出现. 或者,如果您只需要在UI中呈现GUID,请创建GUID指令.例如: .directive("guid",function(){ return { template: "<span>{{getGUID()}}</span>",link: function(scope,element,attrs){ scope.getGUID = function(){ return AppUtilities.getGUID(attrs.guid || attrs.name); }; } } }); 并用作: <h4 class="guid"><guid name="goal"></guid></h4> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |