J
J
JIakki2016-01-15 15:38:47
Angular
JIakki, 2016-01-15 15:38:47

How to load a service on demand?

Can I take the attribute values ​​in the directive and add the service as a dependency in the controller?
If so, how?
Thank you in advance
Code

angular.module('tableData', [])
  .directive('tableData', tableData)

// ################# Логика ################# // 

function tableData() {

  return {
    restrick: 'E',
    replace: true,
    transclude: true,
    template: require('../../template/directives/tableData.html'),
    controller: TableCtrl,
    controllerAs: 'table',
    bindToController: {
      type: '@'
    }
  }
}


function TableCtrl($scope, $filter) {

  var wm = this;
  wm.type // Название
}

There is one option, but maybe you can do better
angular.module('tableData', [])
  .directive('tableData', tableData)
  .service('includeService', function(service1, service2){
    methods = {
      service1: oneService,
      service2: otherService
    }

    return  methods

  //#######################

  function oneService() {
    return service1
  }

  function otherService() {
    return service2
  }

  })

// ################# Логика ################# // 

function tableData() {

  return {
    restrick: 'E',
    replace: true,
    transclude: true,
    template: require('../../template/directives/tableData.html'),
    controller: TableCtrl,
    controllerAs: 'table',
    bindToController: {
      type: '@'
    }
  }
}


function TableCtrl($scope, $filter, includeService) {
  
  var wm = this;
  wm.type // Название

  includeService[wm.type]


}



//################# Конструктори ################# //

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey, 2016-01-15
@JIakki

make stateless directives and life will be a little easier without these perversions. Does the directive need data? Throw them outside through the attributes. Introduce yourself such a simple rule that directives do not receive state themselves through services. And the services should be used by the directive only to update the state of the data outside, but again, they themselves do not change anything.

V
Vladimir Io, 2016-01-15
@vawsan

So look , it seems there is material on this subject.

N
Nicholas, 2016-01-15
@healqq

You get something like hiding dependencies in this case. Why not just inject both services - and use the one you need?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question