如何将自定义函数暴露给angularjs表达式
How to expose custom functions to angularjs expressions
我有一个函数,inArray,我想/需要暴露给angularjs表达式:
功能function inArray( needle, haystack, assocKey ){
assocKey = assocKey || false;
for(var i=0;i<haystack.length;++i){
if( assocKey ){
if( haystack[i][assocKey] == needle ){
return true;
}
} else if( haystack[i] == needle ){
return true;
}
}
return false;
}
有问题的html
<div ng-show="inArray(currentUser.id, item.comments, 'commenter_id')">
You have commented on this already.
</div>
其中一个简化的项目示例是:
item = {
post: 'sfdcsdvsdv',
images: ['1.png','2.png'],
date: 'some date',
comments:[{
commenter_id: 321654987,
comment: 'sdfvsdvsdfv',
date: 'some other date'
},{
commenter_id: 65498721,
comment: 'ptyopoinmu',
date: 'some other date'
}]
}
这段代码甚至没有触及我在全局命名空间中创建的inArray函数。
我认为这是为了安全,即防止糟糕的html运行用户不想运行的危险函数,但是有一种允许设置函数通过的方法吗?
----------
工作答案使用下面的@Martin的回答,我能够把一个工作的解决方案:
过滤器
angular.module('myApp').filter('inArray', function() { // register new filter
return function( input, needle, assocKey ){ // filter arguments
return inArray( input, needle, assocKey ); // implementation
}
});
html <div ng-show="item.comments | inArray:currentUser.id:'commenter_id'">
You have already commented on this
</div>
使用过滤器促进代码重用。将它附加到作用域或rootScope是很糟糕的。使用示例中的函数,您可以执行
angular.module('app').filter('inArray', function() { return inArray });
然后在你的视图
<div ng-show="currentUser.id | inArray : item.comments : 'commenter_id'">
You have commented on this already.
</div>
也就是说,您可能希望颠倒haystack和needle参数的顺序,以便更好地适应习惯用法。
解决方案是将其添加到angular作用域:
$scope.inArray = function( needle, haystack, assocKey ){ .. }
这样Angular就知道inArray函数了。
相关文章:
- 我的AngularJS表达式没有'不起作用
- 在输入中存储AngularJS表达式结果
- 为什么javascript替换方法(没有regex)在angularjs表达式中不起作用来删除 
- Angularjs表达式未显示在ngDialog模板中
- AngularJS表达式未求值
- 使用angularjs表达式复选框
- 如何从json中检索angularjs表达式的数据
- 堆叠三元运算符在 Angularjs 表达式中不起作用
- 如何使真实&&angularjs表达式中的false等于true
- angularjs 表达式中的注释
- AngularJS 表达式不起作用
- AngularJS 表达式在将控制器添加到主体时停止工作
- AngularJS 表达式中的尾随双引号
- 具有多个参数的 AngularJS 表达式过滤器
- 是否可以在 iframe 内更新 angularjs 表达式
- AngularJS 表达式中的条件和循环
- 如何通过http将angularjs表达式内容作为查询字符串发送
- 使用jQuery脚本将CSS样式应用于angularjs表达式
- 将AngularJS表达式传递给PHP或Ajax替代方案
- Flask正在解析AngularJS表达式