Practical AngularJS Part 1 - Sample 4
An example of DOM manipulation by hand replaced with AngularJS, with the last of the requirements implemented
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" ng-disabled="currentUrl.length == 0" />
</form>
<table id="urlTable">
<tr>
<td>Url</td>
<td>Load Speed (ms)</td>
<td></td>
</tr>
<tr ng-repeat="url in urls">
<td><a href="{{url.url}}">{{url.url}}</a></td>
<td><span ng-class="{red: url.loadSpeed > 100}">{{url.loadSpeed | number:0}}</span> ms</td>
<td><a ng-click="removeUrl($index)" href="javascript:void(0)">Delete</a></td>
</tr>
</table>
</div>
CSS
.red {
color: #ff0000;
}
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});
$scope.currentUrl = ""; // Now clear the current URL.
};
// Remove an url.
$scope.removeUrl = function(index) {
$scope.urls.splice(index, 1);
};
}