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

Generating a JavaScript object from a string to optimize its compatibility with datatables

This inquiry pertains to the plugin available at: var hidecols = '{"sClass": "Hide", "aTargets": [0]},{"sClass": "asdf", "aTargets": [1]},{"sClass": "qwer", "aTargets": [2]}'; var hidecolsobj = eval('(' + hidecols + ')'); ...

onsubmit function was never triggered

Seems like a silly mistake, but I'm encountering an issue with my HTML form. Here's a snippet of the code: <form onsubmit="updateProfile();"> <input type="submit" value="Update Account"> .. ... </form> However, w ...

Retrieve the image and insert it using an img tag

Working on a project, I want to include Instagram profile pictures by embedding them. Although I have the image URL, I am struggling to integrate it into my HTML page. Take a look at this sample: This provided link displays the Instagram profile picture. ...

Using Angular to pass an attribute into a directive and utilizing it as a property name on an object

Is it possible to utilize the checkType attribute in a way that resolves as scope.countFrom = sseHandler.broadcastStamp[checkType];? I am attempting to do this in order to easily input the value and create a reusable directive. Currently, I am encounterin ...

Retrieving the previous value using JQuery's onChange event

Is there a way to retrieve the initial quantity value before it is changed with the onChange function in this code snippet? I'm encountering issues with the CSS while using this setup for an input box. You can view the problematic CSS here. Updating ...

Check if an object is already in an array before pushing it in: JavaScript

Summary: I am facing an issue with adding products to the cart on a webpage. There are 10 different "add to cart" buttons for 10 different products. When a user clicks on the button, the product should be added to the this.itemsInCart array if it is not a ...

Retrieve the route parameters and exhibit the default option in a dropdown menu using Angular 2/4/5, along with translations implemented through ngx-translate

Is there a way to extract route parameters from a URL and then display them in a drop-down menu? I've attempted some solutions using ActivatedRoute, but they are not returning the first value after the base reference. For instance, If the URL is: l ...

Ways to remain on the same page even after submitting a form

I've been searching for a solution to my specific issue for days, but haven't had any luck. Can anyone provide assistance? I have a form on my website that is supposed to send an email when clicked, while also converting the div from a form to a ...

Is it possible to resize AngularJS components to fit their parent elements

I am working with a set of LI elements within a document that require their width to be adjusted based on the number of items and the width of the container. How can I access the width of the parent container from this directive? var MyApp = angular.mod ...

Troubleshooting a jQuery Selector Issue with a Dynamic Form

I developed a jQuery function to search for all the necessary inputs in a specific section of a website. function check_property_vars() { jQuery(this).parents('.property_group').find('div[id^="property_group_"]:input[required]:visible&a ...

D3 Treemap for handling extensive sets of data

I am uncertain if there exists a method to incorporate the desired feature. I am seeking a solution similar to zoomable treemaps, but to initially load a limited number of child levels and then dynamically add more child nodes without requiring a node clic ...

Troubleshooting MongoDB and Node.js: Issue with updating variables when inserting documents in a loop

As a newcomer to MongoDB, I'm facing a puzzling issue that has left me confused. In my dataset, I have an array of Employee objects structured like this: { "Name" : "Jack Jackson", "Title" : "Senior Derp Engineer", "Specialties" : [ "Kicki ...

Exporting JSON data as an Excel file in AngularJS, including the option to customize the fonts used for the

Currently, I am working on a project where I need to convert JSON data to an Excel file using JavaScript in combination with AngularJS. So far, I have successfully converted the JSON data to CSV format. However, I faced issues with maintaining the font s ...

An error occurred with the datepicker: Unable to connect to 'bsValue' as it is not recognized as a property of 'input'

Despite importing DatepickerModule.forRoot() in my Angular unit test, I am encountering the following error: Error: Template parse errors: Can't bind to 'bsConfig' since it isn't a known property of 'input'. (" ...

Display the size of the data array in VueJS once the data has been retrieved from the API

Using Vue JS, I have been attempting to retrieve data from an API. My goal is to determine the length of the array and then log it to the console using a method. However, every time I try to do this, the value logged is always "0" instead of the actual le ...

Position the typography component to the right side

Is there a way to align two typography components on the same line, with one aligned to the left and the other to the right? I'm currently using this code but the components are aligned next to each other on the left side. const customStyles = makeSt ...

Switching classes in real time with JavaScript

I'm struggling to understand how to toggle a class based on the anchor text that is clicked. <div> <a id="Menu1" href="#">Menu</a> <div id="subMenu1" class="subLevel"> <p>stuff</p> </div> <div> <a i ...

Issue arises when trying to utilize Ajax on the Fancy Box overlay button click and the functionality does not perform as

Hey there! I've got a bit of a silly question for you. So, I'm pretty new to Ajax and fancy box. I've been using fancy box on one of my pages, and it's been working well so far. The issue I ran into was when I tried to make an ajax call ...

Guide to highlighting manually selected months in the monthpicker by utilizing the DoCheck function in Angular

I'm facing an issue and I could really use some assistance. The problem seems quite straightforward, but I've hit a roadblock. I have even created a stackblitz to showcase the problem, but let me explain it first. So, I've developed my own t ...

I'm encountering an issue with numbers that contain comma decimal separators

My current script is designed to calculate the amount of water saved by a shower column. However, I have encountered issues with its functionality in Firefox and Edge when switching between using "," and "." for values interchangeably. I have attempted va ...