Skip to content

Instantly share code, notes, and snippets.

@lavesan
Last active October 7, 2019 02:47
Show Gist options
  • Save lavesan/82da466a87a76d53cdc15ae9918f1d95 to your computer and use it in GitHub Desktop.
Save lavesan/82da466a87a76d53cdc15ae9918f1d95 to your computer and use it in GitHub Desktop.
Angularjs

Html

<div ng-app="module-1" ng-init="funcaoInicial()">
  <!-- Two way data-binding -->
  <input ng-model="variavel" />
  <!-- One way data-binding -->
  <input ng-bind="variavel2" />
  <select>
    <option ng-repeat="(key, value) in obj1" value="{{ value }}">{{ key }}</option>
  </select>
  <fieldset ng-repeat="value of arr1">
    <input type="text" value="{{ value }}" readonly />
  </fieldset>
</div>

Javascript

Criando um controller (é um componente por assim dizer)

angular.module('module-1', ['finance2'])
.controller('Module1Controller', function Module1Controller() {
  this.variavel = 1;
  this.obj1 = {
    key1: 'value1',
    key2: 'value2',
    key3: 'value3'
  };
  this.arr1 = [
    'value1',
    'value2',
    'value3',
  ];
});

Criando e chamando um serviço (de API ou uma utils que criei por exemplo)

Serviço

angular.module('servico', [])
.factory('funcaoDoServico', function() {
  var currencies = ['USD', 'EUR', 'CNY'];
  var usdToForeignRates = {
    USD: 1,
    EUR: 0.74,
    CNY: 6.09
  };
  var convert = function(amount, inCurr, outCurr) {
    return amount * usdToForeignRates[outCurr] / usdToForeignRates[inCurr];
  };

  return {
    currencies: currencies,
    convert: convert
  };
});

Controller

angular.module('invoice2', ['finance2'])
.controller('InvoiceController', ['currencyConverter', function InvoiceController(currencyConverter) {
  this.qty = 1;
  this.cost = 2;
  this.inCurr = 'EUR';
  this.currencies = currencyConverter.currencies;

  this.total = function total(outCurr) {
    return currencyConverter.convert(this.qty * this.cost, this.inCurr, outCurr);
  };
  this.pay = function pay() {
    window.alert('Thanks!');
  };
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment