Skip to content

Instantly share code, notes, and snippets.

@asduser
Last active May 24, 2016 11:08
Show Gist options
  • Save asduser/cc1f6f75c4ed1e32597add2b792d21ab to your computer and use it in GitHub Desktop.
Save asduser/cc1f6f75c4ed1e32597add2b792d21ab to your computer and use it in GitHub Desktop.
jQuery "ng-repeat" functionality.

ng-repeat using jQuery

Simple implementation Angular's ng-repeat behaviour.

jsfiddle#1 - just elements repeating

jsfiddle#2 - repeating with hardcodded click

jsfiddle#3 - repeating with click

jsfiddle#4 - repeating with click & ability to display a single item like $$item.

<!DOCTYPE html>
<html>
<head>
<title> ng-repeat via jQuery </title>
<style>
.container {
width:540px;
padding:15px 0 15px 15px;
background:#fff;
border:1px solid #ccc;
display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-flex-flow: row wrap;
justify-content: space-around;
}
.user-block {
border:1px solid #333;
border-radius:8px;
text-align:center;
vertical-align:middle;
float:left;
width:130px;
padding:10px;
}
.user-block:hover {
background:lightgreen;
color:blue;
cursor:pointer;
}
.user-block span:nth-child(2) {
font-weight:bold;
}
</style>
</head>
<body>
<div class="container" repeater="user in data">
<div class="user-block">
<span>My name is: </span><span>$$user.Name</span><br/>
<span>I am $$user.Age.</span><br/>
<span>I am from $$user.Country.</span>
</div>
</div>
</body>
</html>
var data = [
{"Name": "Bob", "Age": 20, "Country": "USA"},
{"Name": "John", "Age": 24, "Country": "India"},
{"Name": "Linda", "Age": 25, "Country": "Brazil"}
];
$(document).find("[repeater]").each(function(){
var query = $(this).attr("repeater"),
that = $(this),
queryParam = query.slice(0, query.indexOf(" in")),
queryData = query.slice(query.indexOf("in ") + 3),
internalData = eval(queryData),
externalHtml = $(this).clone();
that.empty();
internalData.forEach(function(el, i){
var result = externalHtml.html(), keys = Object.keys(el), len = keys.length;
for (var j = 0; j < len; j++) {
var temp = "$$" + queryParam + "." + keys[j];
result = result.replace(temp, internalData[i][keys[j]]);
}
that.append(result);
that.append("<br\>");
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment