1

I have to dynamically create a select list in angularjs directive. I have double quote ng-init and ng-options, using angular.element to create the element and append to a div with id preview. the code looks like followings

$('button').click(function() {
     var ng_select_str = '<div class="col-sm-8" ng-init="options=[1,2,3]">' +
                             '<select class="form-control" id="inventory-qq" ng-model="inventory.qq" ng-options="opt as opt for opt in options"></select>' +
                         '</div>';

     var element = angular.element(ng_select_str);
     $('#preview').append(element);
});

however the select list render without any options value(empty select list). I wonder how to solve this problem.

eded
  • 3,778
  • 8
  • 28
  • 42

2 Answers2

2

It is better to have directive for such logics where you can generate and compile dynamic contents.

See simple example below, but it needs some more work

var module = angular.module('testApp', [])
  .directive('test', function($compile) {
    return {
      restrict: 'E',
      replace: true,
      template: '<button ng-click="appendSelectBox()">add select box</button>',
      controller: function($scope, $element) {
        $scope.appendSelectBox = function() {
          var el = $compile('<div class="col-sm-8" ng-init="options=[1,2,3]"><select class="form-control" id="inventory-qq" ng-model="inventory.qq" ng-options="opt as opt for opt in options"></select></div>')($scope);
          $element.parent().append(el);
        };
      }
    };
  });

module.controller('crtl', function($scope) {})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="testApp" ng-controller="crtl">
  <test>text</test>

</div>
Jama A.
  • 15,680
  • 10
  • 55
  • 88
0

You need to compile the element.

var elm = angular.element(ng_select_str);
elm = $compile(elm)(scope);
$('#preview').append(elm);

Your directive should look something like this:

var module = angular.module('app', []);

module.directive('myWidget',
    ['$compile'
        function($compile) {
            return {
                restrict: 'AE',
                link: function(scope, element, attrs) {
                    var elm = angular.element(ng_select_str);
                    elm = $compile(elm)(scope);
                    $('#preview').append(elm);
                }
            };
        }
    ]);
Rob
  • 2,721
  • 1
  • 20
  • 27