javascript - How to expose custom functions to angularjs expressions -


i have function, inarray like/need expose angularjs epressions:

the function

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; } 

the html in question

<div ng-show="inarray(currentuser.id, item.comments, 'commenter_id')">    have commented on already. </div> 

where simplified item example be:

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'   }] } 

this code doesn't touch inarray function, have created in global namespace.

i assume safety, ie preventing bad html running dodgy functions user doesn't want run, there way of allowing set functions through?

----------

a working answer using @martin answer below able put working solution:

the filter

angular.module('myapp').filter('inarray',  function() { // register new filter     return function( input, needle, assockey ){ // filter arguments         return inarray( input, needle, assockey ); // implementation     } }); 

the html

<div ng-show="item.comments | inarray:currentuser.id:'commenter_id'">     have commented on </div> 

use filters promote code reuse. attaching scope or rootscope bad smell. function in example can do

angular.module('app').filter('inarray',  function() { return inarray }); 

then in view

<div ng-show="currentuser.id | inarray : item.comments : 'commenter_id'">     have commented on already.  </div> 

that said, want reverse order of haystack , needle parameters fit idiom better.


Comments

Popular posts from this blog

python - Healpy: From Data to Healpix map -

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -