Create your own AngularJS directive for displaying or hiding elements using ng-show/ng

Caution: Angular rookie in action.

I'm attempting to craft a personalized widget that initially displays a "Reply" link, and upon clicking it, should hide the link and reveal a textarea. Here's my current progress, but unfortunately, it's not functioning as expected:

  .directive('replybox', function ($rootScope) {
    var linkFn = function (scope, element, attrs) {
        var label = angular.element(element.children()[0]);
        scope.showInput = false;

        label.bind("click", showTextbox);

        function showTextbox() {
            scope.showInput = true;
        }
    };
    return {
        link:linkFn,
        restrict:'E',
        scope:{
            id:'@',
            label:'@',
            showInput:'='
        },
        template:'<a ng-hide="showInput">label</a><textarea ng-show="showInput">    </textarea>',
        transclude:true
    };
})

Any advice or guidance would be greatly appreciated. Thank you!

Answer №1

Matias, I have created a working jsFiddle for you to check out: http://jsfiddle.net/pkozlowski_opensource/Z6RzD/

There were several issues at play here, but the most crucial one was the necessity of using Scope.$apply in order for Angular to recognize changes happening outside of its usual scope. By default, Angular does not automatically reevaluate templates with every DOM event, so it needs to be wrapped in an apply function:

scope.$apply('showInput = true');

For more information, refer to this link: http://docs.angularjs.org/api/ng.$rootScope.Scope

Additionally, there are other aspects of your example that warrant attention:

  • If you intend to pass 'label' as an attribute to your directive and use it in your template, remember to use the expression {{label}}
  • The purpose of the 'id' attribute was unclear, so I left it out of my fiddle
  • Similarly, without clear understanding of the intent behind 'showInput', I could not include it in my solution

Answer №2

Using $timeout in Angular can also be beneficial for notifying the framework of any changes, like so:

.directive('replybox', function($rootScope, $timeout) {
  var linkFunction = function(scope, element, attrs) {
    var labelElem = angular.element(element.children()[0]);
    scope.showInputBox = false;

    labelElem.bind("click", toggleInput);

   function toggleInput() {
     $timeout(function() {
       scope.showInputBox = true;
     });

   }
 };
 return {
  link: linkFunction,
  restrict: 'E',
  scope: {
    id: '@',
    label: '@',
    showInputBox: '='
  },
  template: '<a ng-hide="showInputBox">label</a><textarea ng-show="showInputBox">    </textarea>',
  transclude: true
 };
});

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

Tips for eliminating objects with a sessionID:null value from the nested array within an array of objects using JavaScript

[ { "_id": "5ecda7f5310bee6f4b845add", "firstname": "john", "lastname": "smith", "sessions": [ { "_ ...

Automatically adjust multiple images on an HTML webpage

Just starting out with html programming here. Looking to add top margin using a span class, any tips on how to tackle this issue? ...

Is there a way to efficiently use AJAX and PHP to iterate through JSON data and save it to a new JSON file

I have created a simple movie editor with a sidebar where users can drag and drop elements. On the right side, users can edit these elements as they wish and save the data to a JSON file. When the user clicks save, I want it to create a new file and save t ...

Are you utilizing Google Chrome extensions for importing and exporting JSON files?

Currently, I am in the process of developing a Google Chrome extension and I have a question regarding its capabilities. Is it possible for the extension to generate JSON files for users to download (export) as well as implementing a button that allows use ...

What is the best way to pass my request data to my $scope variable?

I'm currently facing a challenge with this particular topic. My goal is to add the response data that I retrieve from Express to my angular $scope and then direct the user to their profile page. This is how my Controller Function is structured: $sc ...

Dynamic Website (Link Relationships / Responsive Design / Content Rendering with CSS and HTML)

Hello everyone! My name is Mauro Cordeiro, and I come from Brazil. I am just diving into the world of coding and have been following various tutorials. Stack Overflow has been an invaluable resource for me in my learning journey! Aside from coding, I am a ...

What is the best way to execute NPM commands within the terminal of Visual Studio Code?

I recently installed npm in VSCode from extensions, but I am having trouble activating it. When I try to run the command 'npm init' in the terminal, I receive the following error message: "The term 'npm' is not recognized as the name of ...

Setting up multiple versions of npm application

Can I have multiple versions of npm installed for different projects on Windows 10, or are npm installations always global? I attempted to install different versions using https://github.com/marcelklehr/nodist, but it only affected the node version and no ...

Activating the Mobile Menu Function when the Window is Resized

I've developed a JavaScript function that triggers on window resize. When switching between landscape and portrait orientation on mobile devices or tablets, the window dimensions change. This functionality is also useful for browser testing on desktop ...

I encountered an error message while running the Angular JS code that I had written, and I am unable to find a solution to resolve it

Every time I attempt to run ng serve, the following error message pops up: "The serve command requires to be run in an Angular project, but a project definition could not be found." I've already experimented with various commands like: npm cache clean ...

Error occurred in next.js environment file when referencing process.env keys as strings in .env.local file

I have a .env.local file with various values stored in it. NEXT_PUBLIC_GA_ID = myvariablevalue I created a function to validate the presence of these values: export const getEnvValue = (name: string, required = true) => { const value = process.env[na ...

Is there a comparison you can make between v-for and a similar feature in Stencil? (such as a functionality akin to v-for

When working with arrays in Stencil, I need to repeat a specific element multiple times based on the array. In Vue, I typically use v-for for this purpose, but what is the equivalent in Stencil? ...

"Can you explain the functioning of this Node.js middleware when it doesn't require any

Currently, I am utilizing a function created by another individual for express and passport, which defines the middleware in the following manner: function isLoggedIn(req, res, next) { if (req.isAuthenticated()){ return next(); } els ...

Unable to execute xmlHttp.responseXML on a server that is offline

Currently, I am diving into the world of AJAX and XML. However, I recently encountered a frustrating issue. I attempted to create a basic program that would display everything I input into an input box within a <div>. Strangely enough, my program fa ...

difficulty encountered during json parsing

I need help accessing displayName in req When I use this code snippet: console.log(req.session.passport.user._raw) The following information is displayed: { "kind": "plus#person", "etag": "\"ucaTEV-ZanNH5M3SCxYRM0QRw2Y/XiR7kPThRbzcIw-YLiAR ...

Tips on initiating a $http.get request every second using a service

I am working on an angular application that includes a $http.get request. While it currently functions properly, I need it to be executed every second in order to retrieve new data. Service: angular.module('adf.widget.liveCharts') .service(&a ...

What is the best way to transform a database object into a complex JSON structure?

My goal is to retrieve a specific person from a list of persons. The POST method works correctly and I am able to obtain the desired person as "chosenPerson" in the controller. However, when I try to convert this person into a complex JSON object using ser ...

The absence of AudioPlayer may be responsible for the compilation failure on Vercel

Here is the latest code snippet import { useState, useEffect, useRef } from "react"; import { FaPlay, FaPause, FaForward, FaBackward } from "react-icons/fa"; export default function Player() { const [isPlaying, setIsPlaying] = useState(false); const [ ...

What is the best practice for incorporating CSS and JavaScript files into a PHP template?

I've created a basic template for my PHP website, but I'm struggling to find the best way to include my CSS and JavaScript files. Take a look at my index.php file below: <?php include'core/template.php'; $temp=new Template(); $sett ...

The functionality of remotely accessing autocomplete in Angucomplete Alt is currently not functioning properly

I'm currently experimenting with AngularJS autocomplete using Angucomplete Alt. I've copied the same code and running it on my local host, but unfortunately, no results are being displayed. When searching for the term 'ssss', an error ...