Add HTML content to an element within a directive and create a custom function to manipulate it locally

In my AngularJS application, I am faced with a variety of complex inputs scattered throughout. Some inputs utilize directives for autocompletion functionality, like those powered by Google Places or Twitter Bootstrap.

I am currently exploring the concept of creating a directive that would mimic the iOS feature of displaying an erase button when text is entered.

Although I attempted to implement this directive, I encountered issues with the scope.erase not initializing, as well as the ng-show not functioning as expected.

Is it feasible to dynamically add HTML elements after the text input and manipulate them within the controller?

Here is the directive I experimented with:

app.directive('eraseBtn', function($parse, $compile){

return {
    require: 'ngModel',
    restrict: "A",
    transclude: true,
    link : function(scope, element, attrs, model){

        element.parent().append('<button ng-click="erase()" ng-show="model.length > 0" class="erase-btn">x</button>');

        scope.erase = function(){
            console.log('Erase test');
        }
    }
}
});

I am reluctant to utilize a template since the HTML structure of my inputs varies significantly.

Answer №1

To dynamically create custom inputs within the link function of your directive based on the model's values, you can utilize the $compile service in AngularJS. This allows you to bind these elements to the model and effectively construct them using directives. Don't forget to invoke the compiled template with the model data.

Sample HTML Code

<!DOCTYPE html>
<html ng-app="demo">

  <head>
    <script data-require="angular.js@*" data-semver="1.2.10" src="http://code.angularjs.org/1.2.10/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-controller="demoController">
    <div demo-directive ng-repeat="input in inputs"></div>
  </body>

</html>

Sample JavaScript Code

angular.module('demo', []).
  controller('demoController', function($scope) {
    $scope.inputs = [{
      inputType: 'checkbox',
      checked: true,
      label: 'input 1'
    }, {
      inputType: 'text',
      value: 'some text 1',
      label: 'input 2'
    }];

    $scope.doSomething = function() {
      alert('button clicked');
    };
  }).
  directive('demoDirective', function($compile) {
    return {
      template: '<div><label>{{input.label}}: </label></div>',
      replace: true,
      link: function(scope, element) {
        var el = angular.element('<span/>');
        switch(scope.input.inputType) {
          case 'checkbox':
            el.append('<input type="checkbox" ng-model="input.checked"/><button ng-if="input.checked" ng-click="input.checked=false; doSomething()">X</button>');
            break;
          case 'text':
            el.append('<input type="text" ng-model="input.value"/><button ng-if="input.value" ng-click="input.value=\'\'; doSomething()">X</button>');
            break;
        }
        $compile(el)(scope);
        element.append(el);
      }
    }
  });

Check out the Plunker for a live example: http://plnkr.co/edit/pzFjgtf9Q4kTI7XGAUCF?p=preview

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

Invoke the do_action function with JavaScript/jQuery

After successfully logging in through Facebook, my AJAX function sends information to the userpro_ajax_url. In order to run a do_action function within the success block, I am trying the following: <?php ob_start(); do_action('userpro_social_l ...

Flot Graphs: A unique dual-axis line chart with the ability to stack data on one axis

Is it possible to utilize the FLOT Javascript library for creating a chart with dual axis and three data sets? I am specifically looking to have one data set on the left axis and two on the right axis. Ideally, I want to stack the two datasets on the right ...

Getting an alert message upon clicking an element in angularjs

I am a beginner in AngularJS and I am attempting to make some DOM modifications when a button/element is clicked. Initially, I'm just looking for guidance on how to achieve the same output as seen in this fiddle link using Angular. Can anyone assist m ...

What is the best way to test an AngularJS directive and monitor function calls with a spy?

After running the code below, an error is thrown mentioning that element.popover is not being invoked. I can't seem to identify what the problem is. Thank you in advance for any assistance provided. directive: angular.module('directives', ...

Is it possible to use the .map() method on an array with only 3 items and add 2 additional placeholders?

I need to iterate through an array of 5 items in a specific way: list.slice(0, 5).map((i) => { return <div>{i}</div> }); However, if the array only contains 3 items, I would like to add placeholders for the remaining 2 items in my reac ...

The challenge of handling scopes in Angular-seed

I am currently facing a challenge with creating a pre-routeProvider post. The problem I'm encountering is that $http is coming up as undefined, even though I am passing it to the function as per my understanding. I have made sure to declare angular.js ...

Creating dynamically generated routes in Angular or Angular 9 before initialization

I'm currently working on a project where I am in the process of converting an AngularJS application to Angular. The main challenge that I am facing at the moment revolves around routing. To sum it up: My requirement is to define routes based on an AP ...

Wait for the canvas to fully load before locating the base64 data in HTML5

Wait until the full canvas is loaded before finding the base64 of that canvas, rather than relying on a fixed time interval. function make_base(bg_img, width, height) { return new Promise(function(resolve, reject) { base_image = new Image(); base_imag ...

Tips on generating a sample Mongoose Model with all null values

Imagine you are working with the following schema: var userSchema = new Schema({ name: String, schools: [{ level: String, name: String, timeInterval: { start: {type:Date,default:Date.now}, ...

What is the best way to eliminate <p><br></p> tags from a summernote value?

When I try to enter text into the summernote textarea for space, I keep getting this code: <p><br></p><p><br></p><p><strong style="font-family: &quot;Open Sans&quot;, Arial, sans-serif; text-align: just ...

Incorporating a new data series into your candlestick chart with Highstock

I've encountered an issue with adding a data series to my candlestick chart in Highstock using Highcharts. Here's the script I'm using: $.ajax({ url : 'indicator', type : 'GET', data ...

React Router will not remount the component when using this.context.router.push

We have implemented a click handler that utilizes react router 2.0 to update the URL with this.context.router.push(). Here is the code snippet: selectRelatedJob(slug) { JobActionCreators.fetchJobPage(slug); JobsActionCreators.getRelatedJobs({'sl& ...

AngularJS - Sending configuration values to a directive

I'm trying to figure out how to pass parameters (values and functions) to an Angular directive. It seems like there should be a way to do this in Angular, but I haven't been able to locate the necessary information. Perhaps I'm not using th ...

Halt the Bootstrap carousel while entering text in a textarea

Is it possible to achieve this? I think so. I have created a carousel with a form inside. The form includes a textarea and a submit button. Currently, the slider does not slide if the mouse pointer is inside it, which is good. However, if the pointer is o ...

What is the proper way to write a function that verifies the presence of a key in an object and then retrieves the associated value?

After holding out for a while hoping to stumble upon the solution, I've decided to give it a shot here on SO since I haven't found it yet. import { PDFViewer, MSViewer } from './viewerclasses' //attempting to incorporate a union of key ...

Sending Node.js variables to HTML with the help of Ajax

I am attempting to pass JSON results from Python to HTML using AJAX in Node.js. My objective is to collect client-side inputs, send them via AJAX to Node.js when a submit button is clicked, and then have the /data middleware execute a Python script that i ...

What is the method for implementing a Redirect in React Router?

I'm new to React and facing a challenge. My goal is to implement a conditional Redirect, and I have created a function called errorCapture for this purpose. The function should trigger a Redirect based on a specific condition. I have included the ret ...

Get Code Now Button

I operate a website dedicated to Amazon reviews, and I am in need of a button that can request a code from a text file uploaded by the seller. My question is how can this be achieved using HTML? I have been experimenting with this sample: <!-- Butt ...

How can I display an array of data with a changing name using a FlatList in React Native?

How can I render a list of array data with a dynamic name in a FlatList using React Native? Below is the list of data that I would like to display in the FlatList: const movies = [ { '4W2JJ0CLbvfLJzBUHORVaz6sAGv2': [ { name: ...

Angular service sending an HTML file instead of a JSON file

After diving into MEAN stack technologies for the past week, I've encountered an issue while trying to utilize a custom service in Angular. My goal is to fetch a .json file, however, upon inspecting the loaded resources in the web inspector when the a ...