Francis.Tricka
Francis.Tricka

Reputation: 15

How to use ng-options and ng-model in an AngularJS custom directive

I'm trying to encapsulate some dropdown list from html code, here is my html code

<custom-dropdown function="foo" data="{{application}}" target="toBeUsedLater">                             
</custom-dropdown>

and here is my custom directive code for customDropdown:

'use strict';

angular.module('sample')
.directive('customDropdown', function () {
    return {
        restrict: 'E',

        scope: {
            data: '@',
            function: '&',
            target: '@',
        },

        link: function (scope, element, attrs) {

            function insertList(obj) {
                var model = scope.function()(obj);

                const list = document.createElement('select');

                //here I want to set the ng-model to whatever target passed in
                list.setAttribute('ng-model', scope.target);     

                //model is a local var, I do not know how to make it work for ngOptions
                list.setAttribute('ng-options', "item for item in model")  

                element.append(list);
            }

            element.on('load', insertList(scope.data));
        }


    };
});

Basically I want to use ngOptions based off of a list that is created locally, and I want to assign the list an ngModel that is passed in as "target", in this case it is called 'toBeUsedLater'. The purpose is to use toBeUsedLater in some html code following the use of this custom directive.

I have tried to us a clumsier way:

 link: function (scope, element, attrs) {

            function insertList(obj) {
                var model = scope.function()(obj);

                const list = document.createElement('select');
                list.setAttribute('ng-model', scope.target);

                //default option
                const option = document.createElement('option');
                option.setAttribute('value', '');
                option.textContent = '--Select--';
                list.append(option);

                for (let i of model) {
                    const option = document.createElement('option');
                    option.setAttribute('value', i);
                    option.textContent = i;
                    list.append(option);
                }

                element.append(list);
            }

            element.on('load', insertList(scope.data));
        }

This renders the list properly but still fails to assign "toBeUsedLater" as the ngModel. Preferably I want to use ngOptions because it is neat. Any help is appreciated, thank you!

Upvotes: 0

Views: 105

Answers (0)

Related Questions