如何将自定义函数公开给angularjs表达式

时间:2015-07-21 19:46:45

标签: javascript angularjs

我有一个函数,inArray,我想/需要暴露给angularjs epressions:

功能

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>

2 个答案:

答案 0 :(得分:0)

解决方案是将其添加到Angular-scope:

$scope.inArray = function( needle, haystack, assocKey ){ .. }

这样Angular就会知道inArray函数。

$ scope对象上的所有内容都可以直接从HTML-Code访问。

答案 1 :(得分:0)

使用过滤器来促进代码重用。将它附加到范围或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>

那就是说,你可能想要改变干草堆和针参数的顺序以更好地适应这个习语。