Superheroic JavaScript MVW Framework



Superheroic JavaScript MVW Framework

0 2


angularjs_presentation


On Github EJIqpEP / angularjs_presentation

Superheroic JavaScript MVW Framework

Presentation created by Kochergin Alexander

Angular JS

is an open-source JavaScript framework, maintained by Google, that assists with running single-page applications. Its goal is to augment browser-based applications with model–view–controller (MVC) capability, in an effort to make both development and testing easier.

Oh hey, these are some notes. They'll be hidden in your presentation, but you can see them if you open the speaker notes window (hit 's' on your keyboard).

History Angular JS

Developed in 2009 by Misko Hevery and Adam Abrons for commercial puproses, but later Angular becomes open-source library.

Hevery, who works in Google, continues to develop and maintain the library.

Version 1.0 of AngularJS was released in December 2012

Design goals:

Decouple DOM manipulation from application logic. Regard application testing as equal in importance to application writing. Decouple the client side of an application from the server side.

Why I choose Angular JS?

It was made by Google It's not in beta Client side MVC HTML Templating Routing Rapid front-end development REST Easy Dependency Injection Easy Two-Way Data Binding Developer happiness It doen't get in the way Large community

Hello world

With Jquery

Html

<input id="name" type="text">
<h2 id="greeting"></h2>

JS

$(function () {
	var name = $('#name');
	var greeting = $('#greeting');
	name.keyup(function () {
		greeting.text('Hello' + name.val() + '!');
	})
})

With Angular JS

<input type="text" ng-model="name">
<h2>Hello {{name}}</h2>

Jquery datepicker in Angular JS

Little reusable code

app.directive "datepicker", ->
  require: "ngModel"
  link: (scope, el, attr, ngModel) ->
    $(el).datepicker('option', 'dateFormat', 'dd/mm/yy')
    $(el).datepicker
      dateFormat: "dd/mm/yy"
      changeMonth: true
      changeYear: true
      buttonImageOnly: true
      buttonImage: '/assets/calendar_icon.png'
      showOn: 'both'
      onSelect: (dateText) ->
        scope.$apply ->
          ngModel.$setViewValue dateText

Usage

<input datepicker="" ng-model="transactionDate">

Structure

How it works

Browser loads the HTML and then the angularjs script. Angular waits for DOMContentLoaded event and looks for the ng-app directive. The module specified in ng-app is used to configure the injector. The injector is used to create $compile service and $rootScope. $compile compiles the DOM and links it with $rootScope. ng-init assigns World to the name property on the scope {{name}} is turned into World

Name into World

<!doctype html>
<html ng-app>
  <head>
  	<script src="angular.js"></script>
  </head>
  <body>
  	<p ng-init="name='World' ">Hello {{name}}</p>
  </body>
</html>

First app in Angular JS

<!DOCTYPE html>
<html ng-app='app'>
<head>
  <title>AngularMoney</title>
  <%= javascript_include_tag "application" %>
  <%= stylesheet_link_tag    "application", :media => "all" %>
  <%= csrf_meta_tags %>
</head>
<body>
  <div ui-view=""></div>
</body>
</html>

main.js.coffee

@app = angular.module('app', [
  # ngResource
  'ngResource',

  # ui-router
  'ui.state',

  'security',

  'app.directives'

])

config/routes.js.coffee

app.config ['$stateProvider', '$urlRouterProvider', ($stateProvider, $urlRouterProvider) ->
  $urlRouterProvider
    .otherwise("/expenses_transactions/new")
    .state "incomes",
      parent: "default"
      url: "/incomes"
      views:
        "":
          controller: "IncomesController"
          templateUrl: "/assets/templates/incomes/index.html.slim"
    .state "incomes_transactions_new",
      parent: "incomes_transactions"
      url: "/new"
      views:
        "@default":
          controller: "IncomesTransactionsController"
          templateUrl: "/assets/templates/incomes_transactions/new.slim"
]
					

ApplicationController.js.coffee

app.controller "ApplicationController", ($scope, security) ->
  console.log 'In ApplicationController'
  $scope.debug = false
  $scope.isAuthenticated = security.isAuthenticated
  $scope.loadLocation = (url) ->
    console.log url
    location.href = url
    			

ExpensesController.js.coffee

app.controller "ExpensesController", ($scope, $http, $location, $state, $stateParams, Expense) ->

  $scope.expenses = {}
  $scope.expense = ''
  $scope.editing = ''

  Expense.query(
    {}

    # Success
  , (response) ->
    $scope.expenses = response

    # Error
  , (response) ->
  )

          

ExpensesController.js.coffee

  if $state.current.name == 'expenses'
    $scope.update = ->
      Expense.update
        id: @editingForm.id.$viewValue
      , expense:
          title: @editingForm.title.$viewValue
          hidden: @editingForm.hidden.$viewValue

        # Success
      , (response) ->
        $scope.editing = ''

        # Error
      , (response) ->

      

ExpensesController.js.coffee

    $scope.cancel = ->
      $scope.editing = ''
      $scope.creating = ''

    $scope.editingToggle = (id) ->
      $scope.editing = id

    $scope.create = ->
      Expense.save(
        {}
      , expense:
          title: @creatingForm.title.$viewValue

        # Success
      , (response) ->
        $scope.creating = ''
        $scope.expenses.unshift(response)
        # Error
      , (response) ->
      )
      

ExpensesController.js.coffee

  $scope.destroy = (id) ->
    Expense.delete
      id: id

      # Success
    , (response) ->
      i = 0
      while i < $scope.expenses.length
        if $scope.expenses[i]['id'] is id
          $scope.expenses.splice(i,1)
        i++

      # Error
    , (response) ->
    			

ExpenseModel.js.coffee

app.factory "Expense", ['$resource', 'TokenHandler', 'apiPrefix', ($resource, tokenHandler, apiPrefix) ->
  resource = $resource( apiPrefix + "/expenses/:id",
    id: "@id"
  ,
    update:
      method: "PUT"
  )

  resource = tokenHandler.wrapActions(resource, ["query", "update", "delete", "create", "get"])
  resource
]
					

index.html.slim

h2 Expenses
.row

  .span9

    a.add-expense  href='#' ng-click='creating=true' ng-hide='creating'
      i.icon-plus
      | Add expense
    .creating-container ng-show='creating'
      form.form-horizontal name='creatingForm'
        .control-group
          label.control-label Expense Name:

          .controls
            input type='text' name='title' ng-model='title'
            div ng-repeat='error in errors.title' {{error}}

        .control-group
          label.control-label Hide from list:

          .controls
            input type='checkbox' name='hidden' ng-model='hidden'

        .control-group
          .controls
            a.btn.btn-primary.create href='#' ng-click='create()' Create
            a.btn.btn-primary.cancel href='#' ng-click='cancel()' Cancel

    .row ng-repeat='expense in expenses'
      div ng-hide='expense.id == editing'
        li ng-class='{hiddenClass: expense.hidden}'
          | {{expense.title}}
        .pull-right
          a ng-click='editingToggle(expense.id)' href='#'
            i.icon-edit
          a ng-click='destroy(expense.id, expense.title)' href='#'
            i.icon-trash
      .edit-container ng-show='expense.id == editing'
        form class='form-horizontal' name='editingForm'
          .control-group
            label class='control-label' Income title
            .controls
              input type='text' placeholder='Title' name='title' ng-model='expense.title'
              div ng-repeat='error in errors.title' {{error}}

          .control-group
            label.control-label Hide from list:

            .controls
              input type='checkbox' name='hidden' ng-model='expense.hidden'
          .control-group
            .controls
              input type='hidden' name='id' ng-model='expense.id'

          .control-group
            .controls
              a.btn.btn-primary href='#' ng-click='update()' Edit
              a.btn.btn-primary href='#' ng-click='cancel()' Cancel

  .span3
    .well
      p
        |
          Welcome to the simple-forum project. This an application designed primarily in AngularJS for a front-end and Ruby on Rails as a back-end.
      p
        |
          Please feel free to leave a comment. Try to keep it civil and clean. Thanks!
          

What we've done

Scaffold gem

				1. gem install angularjs_scaffold
				2. rails g angularjs:install
				3. rails g scaffold Post title:string body:string
				4. rake db:migrate
				5. rails g angularjs:scaffold Posts
					

Scaffold gem

Angular js modules

Angular UI Ng-router Bootstrap Ng-table Http-auth-interceptor Angular-translate Restangular Ng-grid NgInfiniteScroll NgUpload

Usefull links

https://github.com/EJIqpEP/angularjs_presentation Angularjs.org Scaffold gem Egghead.io videos Ngmodules Excel on Angular Literature to learn Angular js JSFiddle example on Angular JS Организация кода в больших AngularJS приложениях

THE END

BY Alexander Kochergin / Elcoding.com