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.
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>