Scope ng-repeat with Angular's $compile function is not functioning as expected

I am facing an issue with my directive that uses the $compile service to create a template. Despite having the users array defined in my scope, it does not populate the select options using either ng-options or ng-repeat. I am puzzled as to why this is happening. The result is just an empty <select> field without any options.

angular.module("myApp").directive("selectForm", [
  '$compile',
  function($compile) {
    return {
      restrict: 'C',
      scope: true,
      link: function(scope, element, attrs) {

        scope.users = [
          { id: 1, name: "User 1" },
          { id: 2, name: "User 2" }
        ];

        element.on('click', function(e) {

          var selectHtml = $compile('\
            <select\
              class="col-lg-2 form-control"\
              ng-options="user.id as user.name for user in users">\
            </select>\
          ')(scope);

          $(element).html(selectHtml);
        });

      }
    }
  }

]);

Answer №1

To get your code working, you need to make a few adjustments:

  • <select> requires ng-model to function properly.
  • Make sure to encapsulate your code within scope.$apply.
  • Use element.off("click") to unsubscribe from the event and prevent flickering.

Check out this DEMO for reference.

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

auto-scrolling webpage as elements come into view

Here is some jQuery code I have: $(".col-md-12").hide(); $(".button-div").hide(); $(".featurette-divider").hide(); $(".footer").hide(); $(".first").fadeIn(1000); $(".second").delay(900).fadeIn(1000); $(".third").delay(1800).fadeIn(1000); $(".fourth").dela ...

Is there a way to transition to a different page while exporting variables within Framework7?

Currently working on a web application using Framework7. I am looking to transition to another page upon clicking a link while also exporting a variable. Within index.php, the following code is present: <head> <script type="text/javascript&g ...

Adaptable Semantic UI form design

Welcome, internet friends! If anyone out there has a moment to spare and is familiar with Semantic UI, I could really use some assistance... Currently, I am working on a form that looks great on larger screens like this: https://i.stack.imgur.com/cafc5.j ...

Is there a variance in window.innerWidth between Chrome and Firefox?

body, html { position:absolute; width:100%; height:100%; margin: 0; padding: 0; overflow: hidden; } When using window.innerWidth, there is a discrepancy between the values returned by Firefox and Chrome. Firefox return ...

Show or hide a fixed position div using jQuery when clicked

I am new to jQuery and I am trying to create a "full page menu" on my own. However, I am struggling to hide the menu on the second click. I tried using .toggle() but I found out that it has been deprecated. Can someone assist me with this? Thank you so muc ...

an issue encountered while trying to print a webpage styled with CSS

Users are given the option to print the current page on the website by clicking on a menu element: <li> <a href="#" onClick="window.print()"> <i class="icon-print"></i> Print Page </a> </li> The page contai ...

The reason behind the clickable issue with my duplicate <ion-select>

I've been working on a form using HTML, CSS, and JavaScript where I implemented an "Add" button to duplicate the form. The issue arises with the ion-select element within the duplicated form. While the original form displays all predefined options upo ...

Failure to trigger AJAX error function when database match is not located

UPDATED: Having some issues with my code entry box when a match is not found in the database. Below are the results for both a good and bad match. Check out my code snippet: function checkDiscountCode() { var discount; if ($('#dbReturnString') ...

Deactivating a button if the input fields are blank using ReactJS

Hi there, I'm new to reactJS and recently encountered an issue with my code. Everything seems to be working fine except for the NEXT button not being disabled when text fields are empty. My expectation is that the NEXT button should only be enabled af ...

Incorporate dots into every slide using the React Slick slider

When implementing a slider in React.js, I use React Slick. The API provided by React Slick allows us to easily incorporate previous and next buttons on each slide using the Previous and Next methods. However, I am curious about how to achieve the same fun ...

How can I showcase the index of `<tr>` and `<td>` elements in a dynamically generated table

How can I print the index of table rows and data on click in javascript? <html> <head> <title>Table Creation</title> <script language="javascript" type="text/javascript"> function createTable() { ...

Observing properties in a unique directive - AngularJS

Background information: I'm currently working on a directive that will monitor the aria-expanded attribute of my bootstrap dropdown menu. My goal is to perform an action when its value changes to false. It seems like using AngularJS for tracking class ...

Issue with Nextjs environmental variables not functioning in JavaScript pages

Currently, I am in the process of developing a Next.js website. Within my JavaScript file, I am fetching data from an API and assigning a token using the .env.local file. However, when attempting to access the .env variable that I've set up, it seems ...

Generating numerous checkboxes dynamically

Seeking assistance with a jQuery function that dynamically generates or clones checkboxes. The challenge is to display the sub_item checkbox when the main_item checkbox is checked. For a demonstration, you can visit this DEMO Jquery $('#btnAdd' ...

jQuery is displaying fields inside the widget box that were supposed to have been removed

I am currently working on a project with a widget foldable box function called Metadata Widget. This widget displays certain fields, and I have added an import button to the side that calls upon the Metadata Widget and shows it. However, I have noticed tha ...

The issue with displaying Fontawesome icons using @import in CSS-in-JS was not resolved

I recently changed how I was importing Fontawesome icons: src/App.css @import "@fortawesome/fontawesome-free/css/all.css";` After shifting the @import to CSS-in-Js using emotion: src/App.js // JS: const imports = css` @import "@fortawes ...

Questions about clarifying JS promises and async-await functions

After doing some reading on promises in JavaScript, I have come across conflicting information which has left me with a few basic questions. I have two specific questions that need clarification: Is it necessary for every function in JavaScript to be ca ...

Angular 2 partial static routing parameters with customizable features

Can an angular 2 routing configuration include a partial-static parameter? Currently, I am using a classic parameter setup like this: const routes: Routes = [ { path: ':type/fine.html', pathMatch: 'full', redirectTo: &ap ...

javascript show and hide navigation bar

I am currently working on a HTML menu that includes a button to open it and an unordered list : <nav class="menu"> <button> <h1>Menu</h1> </button> <ul class="mylist" ...

Calculate the sum of hours worked in a day using pure JavaScript, no external libraries required

Hello, I'm new to this website and please excuse me if my English is not perfect, I am trying my best to communicate :) I have been working on a page that calculates the total hours worked in a day and this is what I have achieved so far until 15/06 ...