Bidirectional Binding with Directive and Controller

I have a dynamic text field being added to the DOM (from a directive link function) and I want to retrieve the entered value and add it to a scope object in the controller. However, I am always getting undefined as the value. Here is my code snippet:

<div class="input-group">
    <span class="fieldIcon input-group-addon"><i class="fa fa-sticky-note" aria-hidden="true"></i></span>
    <select name="addlist[]" multiple="multiple">
        <option ng-repeat="options in optionList">{{options.label}}</option>
    </select>
</div>
<script type="text/javascript">
    angular.module('myapp')
    .controller('AddContactController',[ '$scope', function ($scope) {
        $scope.optionList = [{label: 'NewList'}];        

        $scope.addOption = function(optionList) {
            console.log('List:', optionList); // its giving undefined
            scope.optionList.push(optionList);
        }

    }])
    .directive('optionList', ['$compile', function ($compile) {
        return {
            restrict: 'E',
            templateUrl: '/templates/int_optionList.html',
            controller: 'AddContactController',
            link: function(scope, element, attrs) {
                // Adding input field and on click of a button controllers addOption function should be called with the text field value
                var addListField = '<input class="form-control" type="text" ng-modal="addList" name="addList" placeholder="Add new list...">'+
                +'<button class="btn btn-default" type="button" ng-click="addOption()">';

                addListField = $compile(addListField)(scope);
                $(element).find('.multiselect-container').prepend(addListField);
            }
        }
    }]);
</script>

The issue lies within the addOption function where the value for optionList is coming up as undefined.

Answer №1

Mistakes happen to everyone ;). Make sure to use ng-model instead of ng-modal in your directive

Answer №2

For AngularJS to work correctly, it is important that models are in object form. One way to achieve this is by changing the ng-modal attribute from "addList" to "data.addList."

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

ng-disable will only evaluate when the page is initially loaded

I am facing an issue with around 10 textboxes on a form page. The condition I have is as follows: Disable the textboxes if the logged in user does not have permission Disable the textbox if the user has permission, but there is already a value loaded fro ...

What is the process for sorting a filtered array of strings alphabetically?

Currently, I am navigating through an array in my VUE application that holds the following structured data: [ { "id": 1, "brands": [ { "name": "Mall", "id": 1 }, { "na ...

Showcase a variety of random images in the navigation bar using Javascript and HTML

In order to create a unique experience for mobile users, I have implemented multiple images for my navigation bar menu icon toggle button. These images are stored in an array and a random image is selected each time the page loads using Math.Random. Howeve ...

`React Hook Challenges: Finding a Solution`

I've been experimenting with React to create a basic recipe management application and I've encountered a problem that I haven't been able to solve yet. import { useParams, useHistory, Link } from "react-router-dom"; import useFetc ...

Guide to activating Angular $http redirection during CORS requests

I am encountering an issue with my node/express application that has CORS enabled. Every time I attempt to do a POST request to /login on my app, it redirects to either /failure or /success. However, I always receive the following error message: XMLHttp ...

Using the click function is not possible once the append function has been applied

After adding TRIGGER DIV A above $(".DIVB").html(data); from an AJAX Response, I am unable to trigger code using $(".TRIGGER DIV A").click(function(). Can anyone clarify why this is happening and suggest a solution or workaround? ...

The issue of JavaScript text not being able to be selected persists in Chrome and Internet Explorer

While the text appears fine in Firefox, it remains selectable in Chrome and Internet Explorer. Is there a way to work around this issue? The code snippet was borrowed from another post (which I cannot locate at the moment) so it may be outdated? // To pre ...

Problems with Bootstrap affix scrolling in Internet Explorer and Firefox

I'm encountering an issue with the sidebar on my website. I've implemented Bootstrap affix to keep it fixed until the end of the page, where it should move up along with the rest of the content at a specific point... Everything seems to be worki ...

React-based video annotation/overlay features in the style of Youtube tutorials

Our team is in need of a video annotation system similar to YouTube's. We require the ability to add text/images over videos at specific times. I tried looking for React components or vanilla JS libraries for guidance, but couldn't find any. If ...

Switch between light and dark modes with the MUI theme toggle in the header (AppBar)

I'm currently working on implementing a feature that allows users to switch between dark and light themes in my web app. The challenge I am facing is how to ensure that this theme change functionality is available throughout the entire app, not just i ...

No data will flow through the service to any other controllers

I'm facing an issue with passing data from controller 1 to controller 2. When I try to log the data in controller 2, it shows up as undefined. I decided to use jQuery for data retrieval because I am using datatables and unsure how to bind events with ...

Looping through data in AngularJS to match against specific keys

Here's a sample of what I currently have: scope.exampleModel = { var1: 'data1', var2: 'data2' } _.each(scope.exampleModel, function(detail, key) { if(key === 'var1'){ scope.answer = detail; ...

What is the method for determining the bounding box of a polygon aligned to the viewport

I am facing difficulties in calculating bounding box points accurately when using three.js for rendering polygons in a 2D orthographic camera setup. The simple method of iterating over points to find extreme values does not function correctly after the cam ...

What is the most efficient way to organize these arrays?

I've been racking my brain trying to figure out a sorting logic for some arrays, but I'm stumped. Maybe you have an idea? Imagine we have an array of objects structured like this: let obj = {day:'2', month:'6', year:'19 ...

Storing input data in a dynamic form upon returning to or reloading the page

Currently, my form dynamically adds input fields using code. I am trying to figure out a way to submit the data and proceed to the next page, while ensuring that if someone decides to go back, the newly created input fields will still be populated with the ...

Showing only the results in Codeigniter using Javascript

I'm attempting to retrieve specific data (Latitude and Longitudes) from a query. While the queries appear to be functioning properly and providing outputs, the format of the data is not what I need: [{"latitude":"8.50661","longitude":"124.635"}] The ...

Converting Epoch timestamp to AM/PM format in a React render function

I am currently working on a personal project using React.js. I have successfully fetched an API, and one of the values returned is an Epoch timestamp. My goal is to display this timestamp in a human-readable format such as am/pm. The Epoch timestamp is dis ...

The Express server is failing to deliver a response to the client when using the fetch method

Currently, I am utilizing express for the server side of my project. To send a post request from the client to the server, I am using fetch. The data that I am sending to the server is being successfully transmitted and displayed. However, I am encounteri ...

Filtering pages using the Wordpress API version 2

Is there anyone who can help with the following: I am currently working on building an app in React and using Postman to filter pages. I have set up a Router that is supposed to filter the pages based on which button is clicked. I have experimented with a ...

The concept of abstraction levels within providers, services, and factories in AngularJS

During a recent interview, I was posed with the following question: out of $provider, $service and $factory, which one offers the lowest level of abstraction? While I have experience using all three, my understanding is limited to the syntactic differences ...