Michael Svanström

developer, photographer

Intro to AngularJS

Let’s build a super simple Angular JS 1.0 app!

We’ll assume you have some sort of API at api/aitems and api/aitems/{id} , api/bitems and api/bitems/{id} app.js

(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define([
'jquery',
'angular'
], factory);
} else {
factory();
}
}(function () {
'use strict';

// Declare app level module which depends on filters, and services
var myApp = angular.module('myApp', ['ngResource','myApp.modules.main']);
}
));

  The main module main.js

(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define([
'jquery',
'angular'
], factory);
} else {
factory();
}
}(function () {
'use strict';
angular.module('myApp.modules.main', [])

.controller('MainCtrl', [
'$scope',
function ($scope) {
$scope.aitems = AItems.query();
$scope.bitems = AItems.query();
}])
.factory('AItems', function($resource) {
return $resource('api/aitems/:id',{id:'@id'},{});
})
.factory('BItems', function($resource) {
return $resource('api/bitems/:id',{id:'@id'},{});
})
;

}
));

  The HTML

<!doctype html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular-resource.js"></script>
<script src="app.js"></script>
<script src="main.js"></script>
<link rel="stylesheet" href="todo.css">
</head>
<body>
<h2>Items</h2>
<div ng-controller="MainCtrl">
<ul class="unstyled">
<li ng-repeat="item in bitems">
{{item.title}}
</li>
</ul>
<ul class="unstyled">
<li ng-repeat="item in bitems">
{{item.title}}
</li>
</ul>
</div>
</body>
</html>