簡體   English   中英

如何將自定義函數暴露給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運行用戶不想運行的狡猾函數,但是有沒有辦法讓set函數通過?

----------

一個有效的答案使用下面的@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>

解決方案是將其添加到Angular-scope:

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

這樣,Angular就會知道inArray函數。

$ scope對象上的所有內容都可以直接從HTML代碼訪問。

使用過濾器來促進代碼重用。 將其附加到范圍或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>

就是說,您可能想顛倒干草堆和needle參數的順序以更好地適應該習慣用法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM