"Struggling with the ineffectiveness of the ng-change

I'm having an issue with my custom directive in Angular JS. I've created a function inside the controller that I want to call on an ng-change event from a text box, but for some reason, the function isn't getting called. Here's the code snippet:

<script>
    var delightMeterApp = angular.module('delightMeterApp', []);
    delightMeterApp.directive('delightMeter', function () {
        return {
            scope: true,
            restrict: 'E',
            template: '<div id="delightmeter"></div>',
            link: function (scope, element) {
                // Code for creating the custom meter goes here
            },
            controller: "delightMeterController"
        };
    });
    delightMeterApp.controller('delightMeterController', function ($scope) {
        
        $scope.fun = function () {
            alert("called");
        }
    });
</script>

Here is the relevant HTML:

<div ng-app="delightMeterApp" ng-controller="delightMeterController">
    <delight-meter ng-model="delightScore"></delight-meter>
    <input id="Text1" type="text" ng-change="fun()" />
</div>

I'm unsure if it's correct to use the same controller for both the custom directive and the input control. Can someone point out what mistake I might be making here?

Answer №1

Greetings Sooraj,

Following NexusDuck's advice, it is essential to refrain from manipulating the DOM within your controller. I have made adjustments to your code by relocating the DOM manipulation to the Directive and having the Controller solely execute the Rotate Needle function. The Rotate Needle function is indeed called within the Directive.

Here is the HTML snippet:

<div ng-controller="delightMeterController">
<delightmeter delight-meter-reference='delightMeterReference'></delightmeter>
<input id="txtScore" type="text" ng-model="delightScore" ng-change="delightMeterReference.RotateNeedle(delightScore)" />{{delightScore}}
</div>

This represents your Directive logic:

.directive('delightmeter', function () {
    function link($scope, $element, $attrs) {

        var meter = $element[0];
        console.log(meter);

        // DOM manipulations moved here
       
        // Remaining functions and methods...
      
    }
    return {
        restrict: 'E',
        templateUrl: 'components/comp01/comp01.html',
        scope: {
            delightMeterReference: '='
        },
        link: link
    };
})

Below is your Controller setup:

.controller('delightMeterController', function ($scope) {

    $scope.delightScore = 0;
    $scope.delightMeterReference = {};

})

Thank you for your attention and cooperation!

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 is the best way to retrieve the text node following an element?

Incorporating jQuery. I am faced with this HTML snippet: <input type="checkbox" name='something' value='v1' /> All the world <br /> What selector should I employ in order to exclusively retrieve the text? (I specifically r ...

Tips for Avoiding "TypeError: fetch failed" on Next.js Page Server Component While Retrieving Data from Spring Boot API

Working on a Next.js application has been quite challenging as I fetch data from my Spring Boot API within a Page server component. Unfortunately, my GitHub Action CI/CD pipeline has been encountering failures during the Docker image build process, specifi ...

What is the best way to display a child component inside an iframe using Vue.js?

Looking to provide a live preview of an email before sending it out, I've opted to use an iframe to contain the preview and prevent style leaks. The goal is for the preview to update dynamically as the user fills out form details. How can I display a ...

using lodash to convert objects into arrays while maintaining parent-child relationships

Is there a way to achieve this transformation in lodash or any other JavaScript/TypeScript method? var obj = { a: [ {id:1},{id:2},{id:3}] b: [ {id:4},{id:5},{id:6}] c: [ {id:7},{id:8},{id:9}] } // Need to transform into var arr = [ {title:a ...

Ensuring that localStorage objects continue to iterate when clear() is called within the same function

When a user completes the game loop or starts a new game, I want to clear all local storage while still keeping certain values intact. Currently, I am able to do this for sound volume values: // code inside a conditional statement triggered when starting ...

Clicking our way back through the loop

Looking to display a name when each item is clicked. I've assigned an ID to each element, but it seems like I'm overlooking something. In the current code, I'm thinking there should be a variable involved, but I'm uncertain: $(document ...

Move the DIV element to a static section within the DOM

In my Vue app, I have implemented methods to dynamically move a DIV called 'toolbox' to different sections of the DOM. Currently, the DIV is positioned on the bottom right of the screen and remains static even when scrolling. My goal is to use t ...

Encountering Absent Credentials during Passport Implementation in Node JS and Express

Currently, I am deep in the development phase of an API project. However, I've hit a roadblock while working with Passport as it keeps throwing me an error message stating "Missing Credential". Despite my extensive research efforts, I seem to be at a ...

Angular-UI/Bootstrap: Experimenting with a controller incorporating a dialog box

Hello there, I have a controller that utilizes a Dialog from the angular-ui/bootstrap framework: function ClientFeatureController($dialog, $scope, ClientFeature, Country, FeatureService) { //Get list of client features for selected client (tha ...

What is the best way to save an AJAX response to a class attribute?

I'm currently in the process of creating a model-like Class which, upon initialization, triggers an AJAX request. My goal is to save the response from this request as a property within the new object, allowing me to leverage the returned data. However ...

Is there a way to adjust the dimensions of the circles?

I came across a code that I wanted to customize by changing the size of the circles. Would it be best to do this using JavaScript or CSS? Is there a way to achieve this modification? The complete code can be found at: https://codepen.io/XTn-25/pen/NWqeBaz ...

Which syntax highlighting tool does Google Chrome utilize?

In the Chrome/Chromium inspector, there is a unique syntax highlighter that displays black text while scrolling and highlights after a period of time. This feature differs from Firefox Web Developer Toolbar's highlighting method, which may take longer ...

jQuery smoothly sliding downward from the top to the bottom

http://jsfiddle.net/Hx65Q/3/ Is there a way to make the slider open from the top instead of the left side? $("button" ).click(function() { $('.login').toggle('slide', { duration: 1000, easing: 'easeOutBounce', }); ...

Adjusting the width of the final card in the deck grid

Currently, I am utilizing angular-deckgrid for image display purposes. Within a container, there are two columns in which images are displayed with the column-1-2 class according to the documentation. However, in certain scenarios where only one image is p ...

Crafting Effective AngularJS Directives

Recently, I've been delving into AngularJS and have grasped the core concepts quite well. As I embark on building my own application, I find myself struggling with laying out the blueprint, particularly in terms of directive design. Are there any not ...

What is the best way to organize files by their file names?

Exploring a directory in nodejs and displaying the files. Contents of the directory: -rw-r--r-- 1 coding staff 35 23 Aug 21:34 0.js -rw-r--r-- 1 coding staff 33 23 Aug 21:34 1.js -rw-r--r-- 1 coding staff 41 23 Aug 21:34 2.js -rw-r--r-- 1 coding ...

Whenever you try to access AngularJS, you will consistently be directed to the root

I'm currently attempting to deploy my AngularJS application on a Linux server. However, I've come across an issue where accessing any URL other than '/' automatically redirects me back to '/'. Here is the Nginx configuration I ...

Encountering Angular Material UI issues following the transition from version 11 to 12

I am currently in the process of updating my Angular application from version 11 to 12, integrating Angular Material, and encountering some error messages: Error No.1 - Error NG8002: Cannot bind to 'ngModel' as it is not a recognized property of ...

I am interested in combining identical values within a table

I have identical values in the <td>{{key}}</td> element, and I would like to avoid displaying them repeatedly. Instead, I want to merge them into a single entry. Enter image description here <tbody ng-repeat="(key, val) in myctrl.dep"> ...

Implementing Ajax to insert information, however, the process is prolonged for data insertion

When I use AJAX to insert data into MySQL, pressing the submit button is causing delays in data insertion. I'm hoping someone here can provide better suggestions or feedback. <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.m ...