AngularJS is an amazingly simple, powerful framework and something you should all learn. The simplicity and power of this framework should make any developer excited. This is a cheatsheet to remind me of the general process of creating a typical AngularJS app.
Declaring a new Module
var app = angular.module("myApp", []);
Once a new module is defined you can attach it to any element within the DOM.
<body ng-app="myApp"> ... </body>
App Controller
Used to control the data used in an application. Controllers are regular JavaScript Objects.
myApp.controller('ControllerName', ['$scope', function($scope) { $scope.greeting = 'Hola!'; // additional data is defined here. }]);
Once a controller is declared you can attach it with the ng-controller
directive.
<div ng-controller="ControllerName"> {{ greeting }} </div>
you can also use arrays to store objects inside the app controller.
myApp.controller('People', ['$scope', function($scope) { $scope.persons = [ { name: 'Matthew', occupation: 'Web Developer', age: 27 }, { name: 'Simon', occupation: 'Mechanic', age: 27 }, { name: 'Luke', occupation: 'Builder', age: 27 } ]; }]);
Repeatable Blocks
AngularJS has a neat way to convert arrays into repeatable blocks of HTML with ng-repeat
. This is similar in principal to foreach
loops.
<div class="main" ng-controller="People"> <div class="container"> <h2>People</h2> <div class="people row" ng-repeat="person in persons"> <div class="item col-md-9"> <h3 class="name">{{ person.name }}</h3> <p class="occupation">{{ person.occupation }}</p> <p class="age">{{ person.age }}</p> </div> </div> </div> </div>
Directives
AngularJS directives are extended HTML attributes with the prefix ng-. AngularJS has a number of built in directives.
ng-app
– defines the root HTML element.ng-controller
– defines the application controller.ng-init
– defines initial values.ng-model
– binds the value of HTML controls (input, select, textarea) to application data.ng-repeat
– used to clone HTML blocks. Similar to aforeach
loop.ng-click
– defines an Angular click event.ng-src
– used to correctly return URLs. Replacessrc
.
You can also define a custom directive like so.
app.directive('directiveName', function() { return { restrict: 'E', scope: { info: '=' }, templateUrl: 'pathToTemplate.html' }; });