AngularJS: How to loop through a JavaScript array

I figure that it is time for me to talk a little about AngularJS.  AngularJS is an JavaScript framework for creation of single-page applications.  It was initially released in 2009 by Google.

Let’s look at simple example of what it can do.

<div ng-app>
<h1>Joe’s Skills</h1>

<div ng-controller=”SkillsCtrl”>
<ul>
<li ng-repeat=”skill in skills”>
<h2><a href=”{{skill.BlogURL}}”>{{skill.Name}}</a></h2>

<p>{{skill.Details}}</p>
</li>
</ul>
</div>
</div>

 

function SkillsCtrl($scope) {
$scope.skills = [{
“Name”: “ColdFusion”,
“Details”: “This has been my bread and butter langauge for most of my career.”,
“BlogURL”: “http://steinbring.net/?s=coldfusion”
}, {
“Name”: “Railo”,
“Details”: “It’s what I use for ColdFusion when I’m not at work.”,
“BlogURL”: “http://steinbring.net/?s=Railo”
}, {
“Name”: “jQuery”,
“Details”: “I have used this since way back when.”,
“BlogURL”: “http://steinbring.net/?s=jquery”
}];
}

 

In the above example, we defined an array with three sets of data points in it.  We then looped over the array and populated an unordered list.

We can do better, though.  If you need to define $scope.skills locally, it has limited value.  Let’s use the JSON feed from our CouchDB database instead.

 

<div ng-app>
<h1>Joe’s Skills</h1>

<div ng-controller=”SkillsCtrl”>
<ul>
<li ng-repeat=”skill in skills”>
<h2><a href=”{{skill.value.BlogURL}}”>{{skill.value.Name}}</a></h2>

<p>{{skill.value.Details}}</p>
</li>
</ul>
</div>
</div>

 

function SkillsCtrl($scope, $http) {
jsonFeed = ‘https://steinbring.iriscouch.com/resume_skills/_design/resume/_view/all_skills’;
$http.get(jsonFeed).success(function (data) {
$scope.skills = data.rows;
});
}

So, in the above example, we make use of $http.get().  It works similarly to $.getJSON() in jQuery.  

Want to see the two examples within JSFiddle?  

First Example 

Second Example

Want to see the full-page result?

First Example

Second Example

Leave a Reply

Your email address will not be published.