angularjsangularjs-componentsangularjs-bindings

Angular 1.5. component - what is the best way to distinguish the parent controller via binded property?


I have an AngularJS 1.5 component which represents a select dropdown with ng-options. The specific thing is that these ng-options are filled dynamically with different data (from constant files), depending on the value of the name property which is binded to the component and it comes from the parent controller.
For example, my component looks like this:

test.component.js

angular
    .module('test.component')
    .component('Selector', {
        controller: Selector,
        controllerAs: 'vm',
        templateUrl: 'selector.html',
        bindings: {
            model: '=',
            form: '<',
            name:'@',
            label:'@',
            constant: '<',
        }
    });
    function Selector(CONSTANTS, SOME_OTHER_CONSTANTS) {
        var vm = this;
        switch(vm.name) {
            case 'Name1':
            vm.constant = CONSTANTS;
            break;

            case 'Name2' :
            vm.constant = SOME_OTHER_CONSTANTS;
            break;
        }

    }

So in the view of the parent controller, it is like this:
parent-view.html

<selector
  name="Name1"
  form="vm.myForm"
  model="vm.myModel>
</selector>

It works fine but maybe it is not a good idea to distinguish the parent controller and the data through name property as it is used mostly for form validations. What's better to use in order to distinct the parent controller so to be able to fill different data into ng-options depending on that?

Any help and suggestions would be greatly appreciated.


Solution

  • If you have just 2 of these constants - using if seems ok, if you have like 20 different you can go with injector:

    function Selector($injector) {
            var vm = this;
            vm.constant  = $injector.get(constantProvider);    
        }
    
    <selector
      constant-provider="SOME_OTHER_CONSTANTS"
      form="vm.myForm"
      model="vm.myModel>
    </selector>
    

    If you have multiple places where you want to address constants by name, you can try to make separate factory to store all these small constants:

    module.factory('MyConstants', function(CONSTANTS, SOME_OTHER_CONSTANTS) {
      return {
        name1: CONSTANTS, name2: SOME_OTHER_CONSTANTS
      }
    });