Upgrade to Pro — share decks privately, control downloads, hide ads and more …

AngularJS Introduction

AngularJS Introduction

Oursky Limited

July 09, 2012
Tweet

More Decks by Oursky Limited

Other Decks in Programming

Transcript

  1. What is AngularJS? • Javascript MVC framework for web apps

    • Google funded • Able to create dynamic html views easily ◦ Declarative Markup / UI-binding API ◦ Two way binding ◦ Create custom HTML tags / controls ◦ Testable code
  2. <div ng-app ng-controller="user_list"> <ul> <li ng-repeat="user in people" ng- show="user.enabled">

    {{user.name}} <a href="#" ng-click="disable_user (user)">Disable</a> </li> </ul> <a ng-click="reset()">Reset</a> <hr/> <p>Debug:</p> {{people}} </div> Data binding and controller Demo - http://jsfiddle.net/royuen/xbJQx/ function user_list($scope) { $scope.people = [ {name: 'Ar Cat', enabled: true}, {name: 'Ar Dog', enabled: true}, {name: 'Ar Pig', enabled: true} ]; $scope.disable_user = function(user) { user.enabled = false; } $scope.reset = function() { angular.forEach($scope.people, function (user) { user.enabled = true; }); } }​​
  3. What should controller do? • Controller ◦ Should only contain

    Business Logic ◦ No DOM manipulation there ◦ Testable • DOM manipulation / Presentation Logic ◦ Put in directives • Output filtering ◦ Put in filters ◦ e.g. {{2150 | number}} => 2,150 • External resources ◦ Put in services ◦ e.g. Call RESTful API on server
  4. Directive (as HTML tag) <div ng-app="ballApp" ng-controller="ballCtrl"> <ball color="black"></ball> <ball

    color="{{ball.color}}" ng-repeat="ball in balls" ></ball> <ball color="purple"></ball> </div> Demo - http://jsfiddle.net/royuen/Bckpx/ function ballCtrl($scope) { $scope.balls = [{color: 'blue'}, {color: 'yellow'}, {color: 'brown'}]; } angular.module('ballApp', []). directive('ball', function() { return { restrict: 'E', scope: true, link: function(scope, element, attrs) { scope.$watch(attrs.color, function(color) { element.css('background', attrs.color); }); scope.hide = function() { element.fadeOut(); } }, template: '<div class="ball" ng-click="hide()" ></div>', replace: true }; })​ Demo - http://jsfiddle.net/simpulton/EMA5X/