Wednesday, 3 May 2017

AngulaJs CoffeeScript Grunt

i'm facing to one problem for code optimization ie mangle. I use angular and require and everything worked fine except in service/factory case. There some examples (helloService.coffee)

define 'HelloService', [], ->
   'use strict'
   HS = ($timeout) ->
      sayHello: (name) ->
        $timeout ->
          console.log 'Hello: ' + name
        ,2000
   HS.$inject = ['$timeout']
   HS

And in controller i make something like this:(mainController.coffee)

define 'MainController', ['HelloService'], (HS) ->
  'use strict'
  MC = ($scope) ->
    HS.sayHello 'Stack Overflow' # it return sayHello is not a function
    # do something with scope here
  MC.$inject = ['$scope']
  MC

And there is how app.coffee look like:

define 'app', ['angular', 'HelloService', 'MainController'],(angular, HelloService, Maincontroller)->
  app = angular.module 'app', []
  app.service 'helloService', HelloService
  app.controller 'mainController', MainController

  app.bootstrap = ->
    angular.element(document).ready ->
      angular.bootstrap document, ['app']
  app

And somewhere (main.coffee)

requirejs.config
  baseUrl: ''
  paths:
    angular:['cdn_url','angular_fallback_in_project_dir']
  shim:
    angular:
       exports: 'angular'
       deps: []

require ['app'], (app) ->
  app.bootstrap()

This keep code easier to maintain plus it's really mimification friendly. If i try something like:

hs = new HS()

Then i can call hs.saylHello 'String' but now $timeout is undefined or sometime is not function. Thank in advance for your help.



via Fury45

No comments:

Post a Comment