如何将自定义函数暴露给angularjs表达式

How to expose custom functions to angularjs expressions

本文关键字:angularjs 表达式 暴露 自定义函数      更新时间:2023-09-26

我有一个函数,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函数了。

$scope对象中的所有内容都可以直接从html代码中访问。