Creating a unique AngularJS custom directive that utilizes ng-options can be achieved by populating

I've encountered a major roadblock in my project, and despite my efforts to troubleshoot, I can't seem to find the solution. The issue revolves around populating options within an ng-options directive through a service. This directive is nested inside a custom directive, and I've experimented with various methods including track by and testing the code placement both inside and outside the directive. If anyone could review this snippet of code and identify where the problem lies, I would greatly appreciate it. While the update to ng-model functions properly, the challenge arises during page loading and record selection, wherein the initial option isn't correctly selected. Removing track by resolves the initialization issue but disrupts the ng-model update functionality.

angular
    .module('app')
    .controller('mainCtrl', ['acctList', 'CONSTANTS', 'FORMFIELDS', function(acctList, CONSTANTS, FORMFIELDS) {
        var mainCtrl = this;

        mainCtrl.form = {};

        mainCtrl.formFields = FORMFIELDS;

        mainCtrl.currentRecord = null;
        mainCtrl.editedRecord = {};

        mainCtrl.setCurrentRecord = function(value) {
            mainCtrl.currentRecord = value;
            mainCtrl.editedRecord = angular.copy(mainCtrl.currentRecord);
        };

        mainCtrl.statuses = CONSTANTS.statuses;
    }])
    .value('FORMFIELDS', [
            {
                key: 'active_flag',
                inputtype: 'select',
                type: 'text',
                class: 'form-control',
                id: 'activeFl',
                name: 'activeFl',
                placeholder: 'Active Flag',
                required: true,
                maxlength: 1,
                disabled: false,
                labelfor: 'inputActiveFl',
                labeltext: 'Active Flag',
                field: 'mainCtrl.editedRecord.ACTIVE_FL',
                options: 'list as list.desc for list in mainCtrl.statuses track by list.value'
            }
        ])
    .value('CONSTANTS',
            {
                statuses: [
                    {
                        id: 1,
                        value: "Y",
                        desc: "Active"
                    },
                    {
                        id: 2,
                        value: "N",
                        desc: "Inactive"
                    }
                ]
            }
        )
    .directive('formTemplate', ['$compile', function($compile) {
        function linker(scope, element, attr) {
            scope.$watch(attr.modeltemp, function(modeltemp) {

                // if ngModel already equals modeltemp or modeltemp doesn't exist, return
                if (attr.ngModel == modeltemp || !modeltemp) return;

                // remove all attributes to prevent duplication
                element.removeAttr('placeholder');
                element.removeAttr('type');
                element.removeAttr('class');
                element.removeAttr('id');
                element.removeAttr('name');
                element.removeAttr('ng-required');
                element.removeAttr('maxlength');
                element.removeAttr('ng-disabled');

                // add the ng-model attribute presently tied to modeltemp
                element.attr('ng-model', modeltemp);

                // if modeltemp is blank, then remove ng-model, as it would be null
                if (modeltemp == '') {
                    element.removeAttr('ng-model');
                }

                // Unbind all previous event handlers, this is
                // necessary to remove previously linked models.
                element.off();

                // run a compile on the element, injecting scope, to reconstruct the element
                $compile(element)(scope);
            });

            console.log(scope.acctCtrl);
        }

        // dynamic templating function associated with the templateUrl in the DDO
        function template (tElement, tAttrs) {

            // set the type variable equal to the value from the tAttr for 'inputtype' coming from the view
            var type = tAttrs['inputtype'];
            // just declaring the return variable for cleanliness
            var tpl;
            // begin the switch-case statement for each inputtype, then set it's return variable equal to the respective url
            switch(type) {
                case 'input':
                    tpl = '/common/directives/formTemplate/formTemplate.template.html';
                    break;
                case 'select':
                    tpl = '/common/directives/formTemplate/formTemplateSelect.template.html';
                    break;
                default:
                    tpl = '/common/directives/formTemplate/formTemplate.template.html';
                    break;
            }
            return tpl;
        }

        return {
            restrict: 'EA',
            replace: true,
            templateUrl: template,
            link: linker
        };
    }])
    <form class="form-horizontal" ng-submit="submit()" name="mainCtrl.form.newAcctForm">
<div class="col-lg-6 form-fields" ng-repeat="fields in mainCtrl.formFields" ng-class="{ 'has-error': mainCtrl.form.newAcctForm.{{fields.name}}.$dirty }">
    <label class="control-label" for="{{fields.labelfor}}">{{fields.labeltext}}</label>
    <div form-template modeltemp="fields.field" inputtype="{{fields.inputtype}}"></div>
</div>
    </form>

    <select class="{{fields.class}}" id="{{fields.id}}" name="{{fields.name}}" ng-options="{{fields.options}}" ng-required="{{fields.required}}" maxlength="{{fields.maxlength}}" ng-disabled="{{fields.disabled}}">
<option value="">Please select...</option>
    </select>

Answer №1

Have you thought about utilizing lifecycle hooks instead of this approach, which waits until after the view is fully loaded/initialized? Your method may be effective, but it seems a bit excessive for the task at hand.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using AngularJS to dynamically update the DOM with the response from a service method

Here's the HTML code: <div ng-controller="AutoDeployController as autoDeploy"> <input type="text" ng-model="autoDeploy.message"> <p>Message: {{ autoDeploy.message }}</p> </div> <button ng-click="autoDeploy.chan ...

Learn how to dynamically chain where conditions in Firebase without prior knowledge of how many conditions will be added

Currently, I am working on a project using Angular and firebase. My goal is to develop a function that can take two arguments - a string and an object, then return an Observable containing filtered data based on the key-value pairs in the object for a spe ...

Following the implementation of the YITH ajax navigation filter, my jQuery scripts are no longer functioning as

I'm having trouble with using yith ajax navigation in my theme. Everything works perfectly until I click on an element to filter, at which point my jquery codes stop working. The team at yith suggests: If your product list contains JavaScript cod ...

The function of the React index key appears to be malfunctioning within the map function

I've been encountering issues despite using the index key and also attempted utilizing a unique id from JSON data, but unfortunately haven't found a solution yet. ERROR Warning: Each child in a list should have a unique "key" prop. const fa ...

Invoking PHP code from within Javascript will output the function as a direct string

I seem to be going in circles and missing something silly... My setup involves using CodeIgniter on the server-side and Bootstrap on the client, but that's not really the issue here... I am attempting to access a PHP value within a JavaScript functi ...

Stacking sheets of hole-punched paper on top of one another, create a visually captivating

I am in search of a way to create those distinctive black dots with papers displayed here: body { background: linear-gradient(#ccc, #fff); font: 14px sans-serif; padding: 20px; } .letter { background: #fff; box-shadow: 0 0 10px rgba ...

Click on link after animation has finished

I'm currently facing an issue with my script not functioning correctly. The code I'm utilizing is from a resource provided by Codyhouse to implement a 3D rotating navigation menu on my webpage. Essentially, when you click the hamburger icon, it o ...

React Switch not displaying various pages correctly

After creating a new component to switch between pages on my React app, I encountered an issue where the HomePage renders correctly when entering the site, but clicking on navlinks does not work. Additionally, when trying to access the url /contacto, ins ...

UI-router causing issues with recognizing query parameters

I am trying to route to a state by using the complete URL with query parameters and then perform an action in the controller based on those query parameters. So far, everything works fine when I use a simple routing URL with variables like: "/load/:portNa ...

Add a new division to a component when a specific event handler is triggered by another component using React and the reduce method

Currently, I am developing an interactive drag-and-drop application using React and Redux. My goal is to insert a new div element into a container when the ondragstart event handler is triggered by a component. The component responsible for the dragging o ...

Vue is struggling to load the component files

Lately, I've been encountering an error during webpack build that is causing some issues. ERROR There were 3 errors encountered while compiling The following relative modules could not be found: * ./components/component1.vue in ./resources/assets/ ...

Access and retrieve pkpass files from a server using React

I've exhausted all options but still can't get it to work. I'm attempting to create an Apple wallet pass using https://github.com/walletpass/pass-js. When I download the pass on the node server where I've implemented it, everything work ...

Implement feature to enable selection using jQuery

I have a question about implementing an <option value="fiat">Fiat</option>"> element into a dropdown list using jQuery. I've tried the code below and encountered some issues. When I click the button, I want to add the <option value= ...

The input '{ data: InvitedUser[]; "": any; }' does not match the expected type 'Element'

I'm currently facing a typescript dilemma that requires some assistance. In my project, I have a parent component that passes an array of results to a child component for mapping and displaying the information. Parent Component: import { Table } fr ...

How can a callback be properly passed in programming?

My coding approach is outlined below: var CustomLibrary = (function (window, $, undefined) { return { URI: 'http://testpage/API/', OnSuccess: function (data, status) { }, OnError: function (request, status, error) { } ...

The save functionality is not working due to a JavaScript issue

Having an issue with the save button functionality. The JavaScript code specified for the button seems to interfere with its ability to save information. Interestingly, when I remove the JavaScript it works perfectly and saves the data as intended. (fun ...

Buttons in Datatables fail to appear when using ajax loading

I've been trying to solve this issue for a while now, but I just can't seem to figure it out. According to the documentation, adding initComplete should make the buttons appear, but I am still facing difficulties. Am I overlooking something? I&a ...

Creating a two-column grid layout using Bootstrap 4 is a simple and efficient process. Let's see how

I've been struggling to get this to display side by side in a two-column grid. Even after following Bootstrap tutorials, I can't seem to make it work. Check out the code below: <div class="row"> <div class="col-md-8 ...

Using AJAX to call a PHP function within a PHP script

I have successfully implemented an AJAX file that can execute content from a PHP file. However, my concern is how to specifically call a particular function within the PHP file if there are multiple functions present. Below is my current AJAX code: $(doc ...

Ways to display a variable prior to making an axios request

I have a get request that saves the result in a variable named name_student. How can I access this variable in other methods? Or how should I declare it? Here is the code snippet: getStudent(){ axios.get('https://backunizoom.herokuapp.com/student/2 ...