Search code examples
ruby-on-railsangularjsangularjs-directiveangular-formly

passing a model into a directive in AngularJS


I've got 4 select drop-downs on a page. Below each one I would like dynamic HTML to generate based on the selection using angular-formly.

I have this so far:

ruleSelect.js.erb

angular.module('productsApp')
  .directive('ruleSelect', [
  function() {
    return {
      restrict: 'E',
      replace:  false,
      // require: 'ngModel',
      scope: {
        options: '=',
        ruleBldr: '='
      },
      templateUrl: "<%= asset_path('shared/templates/ruleSelect.html') %>",
      link: function(scope, element, attrs){
      }
    };
 }]);

ruleSelect.html.slim

select.form-control ng-model="value"
  option ng-repeat="field in options | fieldFilter:['templateOptions', 'label']" value="{{$index+1}}"
    | {{field.templateOptions.label}}

form
  formly-form fields="ruleBldr.form[value].fieldGroup"

But on the scope options is set but ruleBldr is empty.

HTML page

.row
  .col-md-offset-6.col-md-6 ng-repeat="obj in ruleB.formObjects"
    label.control-label () {{obj.fieldGroup[0].template}}
    rule-select options='obj.fieldGroup' ruleBldr="obj"

Solution

  • value in ruleB.form[value] isn't defined anywhere.

    If the form is supposed to be created based on the value selected in the <select> you need to add ng-model to <select>. Note that ng-model should always be an object.

    link: function(scope, element, attrs){
       scope.selectModel ={}
    }
    
    select.form-control ng-model="selectModel.value"
    
    formly-form fields="ruleBldr.form[selectModel.value].fieldGroup"
    

    Some of this is a bit of a guess since problem description is very poor. Also I don't know the proper html syntax for your template system

    I'm also not sure if you need the initial value passed into directive from controller