Change the content of a text field in real-time using Angular.js

Looking to make a directive where clicking on a field allows for editing. I want to be able to specify the type of input, such as "textarea" instead of just an input text field. Currently using ng-if for this validation.

https://i.sstatic.net/NAPbj.jpg

However, when I try to implement this, the new dynamic field value is not being saved. How can I troubleshoot this issue?

<div ng-repeat="faq in faqs">
      <a  href='' click-to-edit  ng-model='faq.pregunta'   typeinput='textarea' >{{faq.pregunta}}</a>
</div>

    .directive('clickToEdit', function($timeout,$compile) {

      return {
          require: 'ngModel',
          scope: {
              model: '=ngModel'
          },
          replace: true,
          transclude: false,
          // includes our template
          template:
              '<div class="templateRoot">'+
                  '<div class="hover-edit-trigger" title="click to edit">'+
                      '<div class="hover-text-field" ng-show="!editState" ng-click="toggle()">{{model}}</div>'+
                      //'<span ng-if="type==true">'+
                      '<input class="inputText" type="text" ng-model="localModel" ng-enter="save()" ng-show="editState" />' +
                      //'</span>'+
                      //'<span ng-if="type==false">'+
                      //'<textarea class="inputText"  ng-model="localModel" ng-enter="save()" ng-show="editState" />' +
                      //'</span>'+
                      '<div class="edit-button-group pull-right" ng-show="editState">'+
                          '<div class="glyphicon glyphicon-ok"  ng-click="save()"></div>'+
                          '<div class="glyphicon glyphicon-remove" ng-click="cancel()"></div>'+
                      '</div>'+
                  '</div>'+
              '</div>',

https://jsfiddle.net/ybmrzo5w/

Answer №1

The problem arises from the ng-if directive, which, like other directives, generates a child scope.

To solve this issue, you can utilize an object property in ng-model. This way, even if ng-if creates a new child scope, the changes will still reflect in the parent scope: localModel.value should resolve your situation.

Please refer to the working jsfiddle for a demonstration.

Answer №2

Using an ngIf directive will result in the creation of a child scope. Therefore, when using an ngModel on elements like textarea and input fields, it is important to reference the parent scope as follows:

ng-model="$parent.localModel"

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

No reply received on the web browser

I have written a code that is intended to read a JSON file and display it in the browser. The code is functioning correctly as it prints the data to the console, but for some reason, the data is not displaying on the browser. app.post("/uploadfile&q ...

How can you convert a JavaScript object with nested arrays into JSON format?

I have been working with a JavaScript object that contains nested objects with associative arrays. I attempted to use the stringify function from the json2.js library, but the output did not include the arrays inside the nested objects. In my scenario, I b ...

Guide to implementing sliding effects with Jquery

I recently dived into the world of JavaScript and jQuery. I crafted a piece of JavaScript code for client-side validation. document.getElementById(spnError).style.display = 'block'; Currently, I am displaying a span element if any validation er ...

Updating field based on dropdown value in CakePHP 3.6.11

I have the following tables: customers[id, name, surname, phone, text, balance, created] service_types[id, title, price, length, is_subscription, created] customer_service_types[id, customer_id, service_type_id, price, created] Within the add.ctp file o ...

Removing unexpected keys during validation using Joi

Within my server-side JavaScript code, I am utilizing Joi for validating a JavaScript object. The schema being used is structured as follows: var schema = Joi.object().keys({ displayName: Joi.string().required(), email: Joi.string().email(), e ...

Recursive React components. String iteration enhancement

In my React app, I am trying to create a string hierarchy from an object. The object structure is like this: { name: 'name1', parent:{ name: 'name2', parent:{ name: 'name3', parent: null }}} My plan is to use a state variable ...

When I attempt to run JavaScript code on the server, it fails to execute properly

When I run my code on my PC without putting it on the server, it works perfectly fine. However, when I upload it to the server and try to call it, I encounter the following error: Uncaught ReferenceError: crearLienzo is not defined at onload ((index): ...

Obtain the YouTube video identifier from a YouTube embedded link

Is there a way to extract just the YouTube ID from a given URL? https://www.youtube.com/embed/cqyziA30whE?controls=1&showinfo=0&rel=0&autoplay=0&loop=0 $(".youtube").click(function () { console.log(this.href.replace(new RegExp("em ...

The error message 'mainController' is not recognized as a function and is undefined, version 1.4

When it comes to utilizing newer angular directives like ng-blur, ng-focus, and form validation, the examples abound. They typically perform well in a standalone page or interactive coding platforms like plinkr and jsfiddle. However, there's one commo ...

Retrieving a variable value from an AJAX call for external use

Looking for a solution to pass the generated JSON response from an ASMX web service accessed via AJAX to an outside variable in another function. Below is the code snippet for reference: function setJsonSer() { var strWsUrl = &apo ...

Enhance the functionality of Map.set by automatically storing the new entry on the disk as well

This code is intended for development purposes only, to resume work from where I left off when restarting the local server. I aim to avoid modifying the production code in any way. My goal is to save new entries to disk when using map.set(...). Below is a ...

Tips on implementing live updates in Firebase without the need for reloading the page

After a user changes their profile picture, the update does not appear until they refresh the page. Here is the code snippet causing this issue: const handleProfile = async (e: any) => { const file = e.target.files[0] const storageRef = firebase ...

Events triggered when the mouse hovers over an element and then moves

After spending hours reading articles and watching YouTube videos, I am completely lost. No matter what code I try, it seems like I can never get it right. It's frustrating how such a simple task can be so confusing. I just can't seem to wrap my ...

There was an error in parsing the JSON data due to an unexpected token "u" at the beginning of the string

I've been working on improving my JavaScript skills, but I hit a snag with an error message that reads "Uncaught SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse". var requestData = new XMLHttpRequest(); requestData.open('GET& ...

Change button to an ajax spinner when it is clicked using jQuery

$(".post-btn").html("<img src='../images/loader.gif' />"); Why isn't this code working? I know I have the correct selector because when I tried $(".post-btn").text('test'), it worked. I want the text of the button to change ...

Reactive form allows you to easily format dates

Currently, the date displayed is 1/4/2022. We need it to display in the format 01/04/2022. Can we achieve this formatting using reactive forms with the sample Model form provided below? Thank you. How can we format it when starting from transactionStartD ...

Add a plethora of images to the canvas

Just starting out with Fabric.js and trying to figure out how to draw a picture on the canvas after a drop event. I managed to do it once, but am struggling with inserting more pictures onto the canvas (each new drop event replaces the previous picture). ...

Tips for turning on a gaming controller before using it

Current Situation In my ionic side menu app, I have a main controller called 'main view'. Each tab in the app has its own controller, which is a child of the main controller. The issue I'm facing is that when I start the app, the first cont ...

What is the process for setting up Vue.js and using it in conjunction with Sails JS?

After successfully setting up the backend of my website using Sails JS, I decided to integrate Vue.js into my project. Following the installation of Vue and VueResource through npm install --save, I created an app.js file in my assets/js folder. However, ...

Implementing jQuery/JavaScript to efficiently iterate through JSON data

I have implemented a form that allows users to select an item from a multi-select dropdown (A). If the desired item is not listed, users can manually add it using another text input box (B). Once added, an AJAX call saves the item to the database. After su ...