Filling in input field attributes using a custom directive

Here is a JSFiddle link for reference:

http://jsfiddle.net/DfLdF/

The issue I am facing involves a controller wrapping a form with certain logic that cannot be defined within the directive hash as a controller. Specifically, I need to dynamically populate a field from a directive in the following manner:

 App.Directive.SomeAwesomeDirective = ->
     restrict: 'C'

     link: (scope, element, attrs) ->
         someValue = scope.someValue
         field = element.find(".some-class")
         scope.fieldValue = someValue
         field.ngModel = "scope.fieldValue"
         field.ngClass = "scope.someAwesomeClass"

         monitorFields = (newValue, oldValue) ->
              console.log "we are here"
              console.debug newValue
              console.debug oldValue
              scope.addValue(newValue)

         scope.$watch "scope.fieldValue", monitorFields, true

The requirements for this task include:

1) Updating scope.fieldValue when the textfield's value is changed. 2) Triggering the addValue method (defined on the wrapping controller) to validate the new value once it has been updated. 3) The addValue method should set the someAwesomeClass scope variable and update the input field's class accordingly. 4) Applying ng-valid/ng-invalid classes for proper form validation based on the aforementioned conditions.

The current jsfiddle demonstration does not exhibit the desired behavior, and I am seeking assistance in resolving this issue...

Thank you!

Answer №1

If you encounter an issue, it can be resolved by creating a directive called someClass. This directive will trigger the function on its parent element. Additionally, add the execute attribute to the form tag with the desired function for execution. The someClass directive will locate the controller of the dir directive (hence require: '^dir') and execute it accordingly.

Alternatively, you could skip using the dir directive and instead incorporate the execute attribute directly into the someClass directive (e.g. when each input field needs to activate a different function).

<form class="dir" execute="someFunction">

Custom Directives:

app.directive('dir', function () {
  return {
    restrict: 'C',
    scope: {
      execute: '='
    },
    controller: function ($scope) {
      this.execute = $scope.execute;
    }
  };
});


app.directive('someClass', function () {
  return {
    restrict: 'C',
    require: '^dir',
    replace: true,
    template: '<INPUT name="foo" id="bar" type="text" ng-model="fieldValue" >',
    scope: {
      fieldValue: '@'
    },
    link: function (scope, elm, attrs, ctrl) {
      var monitorField = function (newValue, oldValue) {
        if (newValue) {
           ctrl.execute(newValue);
        }
      };
      scope.$watch("fieldValue", monitorField, true);
    }
  };
});

Check out the example on jsFiddle.

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

What could be the issue with injecting form information into a MySQL database with Node.js?

Currently, I am developing a web application for my school which requires me to create a login and register page. To achieve this, I have chosen to utilize node.js, express, and mysql. As I am still relatively new to node.js, I encountered an issue while t ...

Utilizing Selenium Webdriver to efficiently scroll through a webpage with AJAX-loaded content

I am currently utilizing Selenium Webdriver to extract content from a webpage. The challenge I'm facing is that the page dynamically loads more content using AJAX as the user scrolls down. While I can programmatically scroll down using JavaScript, I a ...

Issue with Vue 2: Promise does not resolve after redirecting to another page

Although I realize this question might seem like a repetition, I have been tirelessly seeking a solution without success. The issue I am facing involves a method that resolves a promise only after the window has fully loaded. Subsequently, in my mounted h ...

The calculation of Value Added Tax does not involve the use of jQuery

My form setup is as follows: <form method="post" action="" id="form-show"> <table class="table table-bordered table-striped table-hover" id='total' style="width:100%;"> ...

What is the process for a browser to load JavaScript resources?

I decided to do some research on how browsers load resources like CSS, JS, Images, HTML, etc. After creating a prototype code based on my findings, I became a bit confused during testing. Below is the Plnkr code where I included a <script> tag to int ...

implementing conditional logic in angularjs expressions

<p>{{isExisted}}</p> Looking to show either "Active" or "Inactive", but the isExisted variable only returns true or false. Need help with setting up a conditional if else statement to change it to the desired value. ...

Tips for integrating both client-side and server-side validation techniques in your web application

After conducting some research, I have come across information indicating that it is feasible to implement both client-side and server-side validation simultaneously. However, my focus is not solely on learning JavaScript; I am also interested in utilizi ...

Disabling JavaScript with InternetExplorerDriver in Selenium

Is there a way to turn off JavaScript when using the InternetExplorerDriver? I've tried the code below, but it doesn't appear to disable JavaScript: self.selenium = webdriver.Remote( command_executor="http://localhost:4444/wd/hub", desire ...

The Highcharts backgroundColor feature does not apply to more than one chart at a time

The example below is hosted on jsfiddle and can be accessed through this link: http://jsfiddle.net/KWqU2/2/ Both Highcharts have a backgroundColor defined in the chart options settings. However, the issue is that the second chart seems to always default ...

Finding the Closest Element with jQuery's .closest() Method

I'm facing an issue while trying to select an element that is positioned above another element. Specifically, I want to target the nearest occurrence of the .discount-dropdown class that appears above the .discount-type class. Can anyone help me figur ...

The function does not modify the content of an element in Internet Explorer versions 10 to 11

I'm currently working on a layout that needs to support IE10-11. Everything seems to be functioning well overall, except for the .text jQuery method. My goal is to have certain elements change their text when a button on the page is clicked, based on ...

Is it possible to collaborate using Ionic 2 and AngularJs 1?

Aspiring to create applications using Ionic 2, I am currently utilizing AngularJS1 with Ionic1. Although I find AngularJs 1 to be more familiar, AngularJS 2 poses a challenge. Is there a method to integrate Ionic 2 with AngularJS 1 seamlessly? ...

Steps for adding a thought bubble over an image using CSS

Currently, I am working on a project where users can upload an image and based on that image, a thought bubble or speech bubble is placed on top. I need to make sure the placement is just right, but my main priority is getting a functional version up and ...

Converting milliseconds into a formatted DateTime using AngularJS: A step-by-step guide

Upon receiving JSON data from the server, I obtained a date-time in milliseconds: $scope.JDT = "1492499995056";. While I am able to display the scope variable 'JDT' on my view using a filter: {{JDT | date:"dd/MM/yyyy h:mm:ss a"}} ... I do not a ...

Achieving the Low Poly Aesthetic with Three.js

I'm attempting to generate terrain in the low poly style, characterized by each triangle being one shade. However, my efforts have resulted in very smooth shading. An example with a few triangles can be seen here: https://i.sstatic.net/cZSBe.png ( ...

Every time I invoke a module, non-global variables are utilized

Within a module.exports file, I am facing an issue where the variables are shared among different instances of the module. Instead, I want each call to the module to have its own set of values for cycle number, original data, new product, etc., similar to ...

My div does not refresh when using .load

I implemented ajax to retrieve the start time and end time from another page, and used setInterval to call this function every second like so. setInterval(function () { CheckTime() }, 1000); function CheckTime() { $.ajax({ url: "Get_TIme. ...

Trigger the errorPlacement function of the jQuery Validation Plugin on events like onfocusout, keyup, and click

Currently, I am utilizing the jquery validation plugin and aiming to utilize the errorPlacement function in order to include error messages to the fields title attribute and display only a ✘ next to the field. Everything works as intended when the form ...

Ways to send a variable to ngIf

header.component.html <ng-container *ngFor="let headerMenu of headerMenus"> <li *ngIf="headerMenu.ngif"> <a (click)="onClick(headerMenu.menu)" [class]="headerMenu.menu"> <img [src]="headerMenu.src" [alt]="heade ...

Ensuring my Mongo connection string is accurate for hosting a remote database with authorization

Having difficulty replicating the MongoDB connection in NodeJS using Mongojs. mongo --host dds-xxxx.mongodb.rds.aliyuncs.com:3717 -u root -p password --authenticationDatabase admin Here is my current code snippet: /* MongoDB setup */ // Define parameter ...