Currently, I am working on dynamically inserting an ng-options
directive within various <select>
elements throughout my application. These elements have their own unique class names and other directives, such as ng-if
, among others.
<div ng-app="app" ng-controller="ctrl">
<select ng-model="model" class="myClass" ng-if="condition || true" my-directive>
</select>
<pre>{{ model | json }}</pre>
</div>
angular
.module('app', [])
.directive('myDirective', function($compile) {
return {
restrict: 'A',
scope: false,
link: function($scope, $elem, $attr) {
$scope.items = [{ label: "foo", value: "foofoo"},
{ label: "bar", value: "barbar"}];
$elem.removeAttr('my-directive'); // Prevents infinite loop
$elem.attr('ng-options', 'item as item.label for item in items');
$compile($elem)($scope);
}
}
})
.controller('ctrl', function($scope) {
$scope.model = null;
$scope.$watch('model', function(val) { console.log('•', val) });
});
The objective is to replace my-directive
with ng-options
, while ensuring that the element behaves as usual with all its other applied directives.
I'm puzzled as to why ng-model
isn't getting updated, considering the directive's scope is set to the parent scope (scope: false
). I attempted to make DOM modifications during the compile step of the directive, but the dropdown menu failed to populate despite defining $scope.items
.