Retrieve default HTML from an AngularJS directive

Currently, I am in the process of creating an AngularJS directive and require the ability to extract the HTML content of an element before replacing it with a template. For instance:

<edit>Default title</edit>

The structure of my directive is as follows:

.directive('edit', function() {
    return {
        restrict: "EA",
        scope: {},
        template: '<h1 ng-show="!edit_mode">{{variable.value}}</h1><input ng-show="edit_mode" ng-model="variable.value" />',
        link: function( scope, element ) {
            scope.edit_mode = false;
            scope.variable = {
                value: element.html() 
            }
            console.log( scope.variable );
        }
    }
});

However, upon checking the console output (and the webpage), I noticed the following:

Object {value: "<h1 ng-show="!edit_mode" class="ng-binding">{{variable.value}}</h1><input ng-show="edit_mode" ng-model="variable.value" class="ng-pristine ng-valid">"}

Answer №1

The sequence of steps in the compiling process is as follows:

  • Transcluding elements
  • Replacing the templates
  • Executing compile functions
  • Creating scopes
  • Instantiating controllers
  • Executing pre linking function
  • Executing post linking functions

During the execution of the linking function, the original template has already been replaced. To properly handle this, it is recommended to store the original template before replacing it with a new one:

app.directive('edit', function() {
  return {
    restrict: "EA",
    scope: {},
    template: function(tElm, tAttrs) {
      tAttrs.value = tElm.html();
      return '<h1 ng-show="!edit_mode">{{variable.value}}</h1><input ng-show="edit_mode" ng-model="variable.value" />';
    },
    link: function( scope, element, attrs ) {
      scope.edit_mode = true;
      scope.variable = {
        value: attrs.value
      };
    }
  };
});

Answer №2

I enjoyed

<edit data="Custom title">Custom title</edit>

.directive('edit', function() {
return {
    restrict: "EA",
    replace: true,
    scope: {
      data: "@"
    },
    template: '<h1>{{variable.value}}</h1',
    link: function( scope, element) {
        scope.variable = {
            value: scope.data
        }

        console.log( scope.variable );
    }
}

Check out this demonstration http://plnkr.co/edit/8XphUri8PBMAHKNlfFMu?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

The functionality of Flatbutton(Input handler) appears to be malfunctioning

I am having trouble with the file uploader from Material-UI. It doesn't seem to be working properly when I try to select a file. Does anyone have any suggestions on how to handle the input from the file selector? <FlatButton icon={< ...

Pressing the menu button will trigger a function that halts after the third click

As I attempted to implement the functionality of this left menu bar, I encountered a roadblock. The click event on the menu button seems to work fine initially - the left bar appears with the first click and closes as expected with the second click. Howeve ...

Retrieve all direct message channels in Discord using DiscordJS

I need to retrieve all communication channels and messages sent by a bot. The goal is to access all available channels, including direct message (DM) channels. However, the current method seems to only fetch guild channels. client.channels.cache.entries() ...

Guide on verifying the ng-valid status of all inputs within an AngularJS table

I'm working with a table where each row contains an input field. Here's the code snippet: When the save button is clicked, I need to go through each input and determine if it's ng-valid. <div class="line" data-ng-repeat="data in datas"& ...

Tips for reconstructing a path in Raphael JS

I am encountering a unique issue with my implementation of Raphael JS. Currently, I am working on drawing a donut element and seeking advice similar to the content found in this helpful link How to achieve 'donut holes' with paths in Raphael) var ...

The second pop-up modal fails to appear

I have successfully implemented 2 modal windows with the help of bootstrap. The first modal is used for adding a user to the database, and the second one is meant for editing an existing user. While the first modal works perfectly fine, the editing modal d ...

Carousel with Bootstrap: Heading positioned over the content

My goal is to have the caption of Bootstrap Carousel displayed above the content, but I'm encountering issues with it. When clicking on the chevrons, you may notice the < Item 1 > bouncing... (This behavior is a bug, and logically speaking, I ex ...

Real-time webpage featuring dynamically updating text sourced from a file

After spending 5 hours attempting this on my own, I've decided to reach out for help. I am in need of creating a page that will automatically update itself and display the content of a file when it changes. For example, let's say we have a file ...

Crafting a radiant sun with ThreeJS

I am working on designing a solar system in WebGL but I am facing challenges with setting up the lighting. My main goal is to incorporate a light source within the sun that casts light in all directions, while ensuring that my planets can both cast and rec ...

Choose the initial search result without actually opening it using jQuery

I am working on an HTML file that contains multiple input fields, which get automatically filled when a corresponding item is selected from the auto-complete feature. Here is a snippet of my HTML code: <table class="table table-bordered"> <u ...

gulp-watch does not monitor files that are newly created or deleted

Currently working on a task: gulp.task('assetsInject', function () { gulp.src(paths.index) .pipe(plugins.inject( gulp.src(paths.scripts, {read: false}), { addRootSlash: false } ...

I am facing difficulties with the header in CSS as it is not resizing properly

I'm having trouble getting my mobile-first design to work properly because the header doesn't resize in mobile view. I'm satisfied with how it looks in full-screen, but I haven't been able to make any media queries work. You can downloa ...

Using an object as an array index in Javascript

I have been utilizing a crossword application from this specific repository: https://github.com/jweisbeck/Crossword . The issue I am facing is that the program is using jquery version 1.6.2 while my entire project is built on jquery-3.1.1 version. The erro ...

Tips on maintaining and storing values for every loop and filling HTML rows correspondingly

Our task is to store the value of each iteration and then load these values into corresponding HTML rows. The server will provide dynamic responses: (based on the key selected by the user) Key:"Apple" values:0:Array[2] 1:"500" 1: Array[2]0:""1:"765" "Key: ...

Troubleshooting: Issue with fixed positioning in React (Next.js) causing problems with modal window functionality

I'm currently working on implementing a modal window in React, but I've encountered an issue where setting position: fixed results in the modal window's position being relative to the page rather than the browser window. For privacy reasons, ...

Having trouble with logging in/out, registration, and my submitPost function has suddenly ceased to work

Grunt is not showing any errors and when using the debugger "Error: [$injector:unpr] Unknown provider: AuthProvider <- Auth <- user <- NavCtrl also "Error: [$injector:unpr] Unknown provider: AuthProvider <- Auth <- user You can find the ...

Is there a way to add text to HTML code using CKEditor?

I incorporate CKEditor into my website. When I click on a specific link, it adds some text to the editor successfully. However, when I switch to the source tab, I am unable to append this text to the existing source code. Can anyone offer guidance on h ...

Guide to configuring angular-rails 4.2 with devise for user registration and authentication

Do you have any recommendations or resources related to this topic? I grasp the theory behind it, but I've also heard about JWT etc. What are the most effective methods for implementing role-based authentication/registration in a device/angular/rails ...

Include HTML tag and class inside a JavaScript code block

A dynamic button is loaded when a certain condition in the JavaScript is met. Upon loading, I want to trigger a function (ClickMe) by clicking the button. However, I'm facing difficulty connecting the function with the button in my code. In my scrip ...

Unable to reach the form within the AngularJS controller

Having trouble accessing a form variable from my controller. When I try to access it using $scope.locationForm, it returns 'undefined'. However, when I use console.log($scope), I can see the locationForm in the console. Here is my HTML code: &l ...