代码之家  ›  专栏  ›  技术社区  ›  user1037355

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

  •  0
  • user1037355  · 技术社区  · 11 年前

    我有一个函数,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>
    
    2 回复  |  直到 11 年前
        1
  •  0
  •   matthiasgiger    11 年前

    使用过滤器促进代码重用。将其附加到作用域或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>
    

    也就是说,您可能希望颠倒大海捞针参数的顺序,以更好地适应习惯用法。

        2
  •  0
  •   matthiasgiger    11 年前

    解决方案是将其添加到Angular范围:

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

    这样Angular将知道inArray函数。

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