Practical AngularJS Part 1 - Sample 3
An example of DOM manipulation by hand replaced with AngularJS
by Dave Kerr
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<div ng-app ng-controller="SpeedmonitorController">
<h3>Speedmonitor</h3>
<form ng-submit="addUrl()">
<label for="url">Url</label>
<input id="url" type="text" ng-model="currentUrl" />
<input id="submit" type="submit" />
</form>
<table id="urlTable">
<tr>
<td>Url</td>
<td>Load Speed (ms)</td>
<td></td>
</tr>
<tr ng-repeat="url in urls">
<td>{{url.url}}</td>
<td>{{url.loadSpeed}} ms</td>
<td><a ng-click="removeUrl($index)" href="javascript:void(0)">Delete</a></td>
</tr>
</table>
</div>
JavaScript
function SpeedmonitorController($scope) {
// The current url we're preparing to add.
$scope.currentUrl = "";
// In this array, we'll keep track of the urls and their last fetch time.
$scope.urls = [{url: "www.google.com", loadSpeed: 50},
{url: "angularjs.org", loadSpeed: 75},
{url: "www.dwmkerr.com", loadSpeed: 120}];
// Adds an url.
$scope.addUrl = function() {
$scope.urls.push({url: $scope.currentUrl, loadSpeed: Math.random() * 75 + 50});
};
// Remove an url.
$scope.removeUrl = function(index) {
$scope.urls.splice(index, 1);
};
}