Unnoticed modification to an Angular directive's attribute

I'm encountering an issue with an Angular directive.

I'm trying to create a directive that can "change itself" based on an attribute. Unfortunately, the watcher on the attribute isn't detecting any changes.

Here is a fiddle in JavaScript that illustrates my problem: http://jsfiddle.net/gmjm84m1/ (When you change 'something', the watcher doesn't react. However, if you inspect 'here', you can see that the content attribute has changed...)

HTML

<div ng-app="myDirective" ng-controller="x">
<div content="{{something}}" my-directive>
    <p>here</p>
</div>
<p>{{something}}</p>
<input type="text" ng-model="something"></p>

JS :

angular.module('myDirective', []).directive('myDirective', function () {
  return {
    restrict: 'A',
    link: function (scope, element, attrs) {
        scope.$watch(attrs.content, function (v) {
            console.log('value has changed, new value is: ' + v);
        });
    }
  };
});

function x($scope) {
  $scope.something = "yolo";
}

Can someone help me understand why this isn't working? Is there a different approach I should take?

Answer №1

Less than ideal solution:

    restrict: 'A',
    link: function (scope, element, attrs) {
        scope.$watch(function () { return attrs.content }, function (v) {
            console.log('value changed, new value is: ' + v);
        });
    }

Optimal solution:

   restrict: 'A',
    scope: {
        content: '@'
    },
    link: function (scope, element, attrs) {
        scope.$watch('content', function (v) {
            console.log('value changed, new value is: ' + v);
        });
    }

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

Using JQuery to deactivate a button based on a specific select option

Once a user selects and submits an option from the dropdown list of collections in my form, I aim to disable the button so that they cannot submit that same collection again. Although Ajax is functioning properly and successfully disables the button upon s ...

Is it possible for me to run two processes simultaneously on the same server - one to handle incoming requests and another to continuously poll a data storage system?

I am currently in the process of developing a server with two main functions: An API that can create, update, retrieve, and delete data in a local storage (similar to managing files on the server for a project prototype) A continuous loop that monito ...

What causes a delay of one iteration in the $location.search method when used within the _.debounce() function in lodash?

In the code snippet below, I encountered an unexpected behavior: $scope.$watch('filters', _.debounce(function(newValue, oldValue) { $location.search({test : newValue}).replace(); }, 500), true); What's happening is that the URL only ...

Is it necessary for me to be concerned about developing a separate module for every controller, service, directive, etc

It has come to my attention that some individuals opt to create a new module for every controller, service, directive, and so forth. angular.module('controllers.Dashboard',[]).controller(...); angular.module('controllers.Details',[]).c ...

Make sure to prevent the submit button from being activated if there is any white space present in the

<form name="regForm"> <input type="text" id="username" name="username" ng-model="username" required> <button ng-click="submitSignup()" type="submit" ng-disabled=" (regForm.username.$dirty && regForm.username.$invalid) || regForm.use ...

Establishing a Connection with Node/Express Routing via JavaScript

When developing a web application using HTML, JavaScript, and Node.js with Express, I often find the need to navigate between pages based on user actions. In HTML, one approach is to add an href link and then set up routes in my app.js file to handle the ...

Designing Buttons and Titles for the Login Page

I'm currently working on developing a straightforward login page in react native and I've encountered some difficulties with styling. Does anyone have tips on how to center the text on the button? Also, is there a way to move the INSTARIDE text ...

Having trouble loading an image after successfully connecting to an API with react.js

I've been working on a custom fetch component to load images from the "the dog API" onto my page. However, I'm facing some issues with getting the images to display correctly. Can anyone spot what might be missing in my setup? App.js import &apo ...

Updating React state via child components

Encountering a strange issue while working on a project, I managed to replicate it in this jsfiddle. The parent component's state seems to be affected when the child component updates its state. Any insights on what might be causing this? Here is the ...

Ways to halt a message callback?

Looking at some lines of code from a canvas sprite animation on GitHub, I am curious about how to stop the animations once the sprite has finished. window.requestAnimFrame = (function(callback) { // Function for handling animation frames return window.r ...

Guide to writing a unit test for a parameter decorator in NestJs

I want to implement a unit test for a basic custom decorator that I created, but I'm facing some challenges. This decorator was developed based on the solution provided here. I have Keycloak authentication set up and using this solution in my controll ...

Querying MongoDB findAndModify: <<< locate and modify an object within an array in a document

Question : I am attempting to locate an object within a document's array and make updates to it. The syntax below provides me with the desired object, but I am unsure of how to update it. I attempted to use this query in findAndModify, but it seems ...

the ajax method is not being executed

My specific requirement is to retrieve values returned from my aspx page in an HTML page. Thank you in advance for your assistance. <script type="text/javascript"> function getCars() { alert("Hello"); $.ajax({ type: "POST", ...

What is the best way to detect the presence of the special characters "<" or ">" in a user input using JavaScript?

Looking to identify the presence of < or > in user input using JavaScript. Anyone have a suggestion for the regular expression to use? The current regex is not functioning as expected. var spclChar=/^[<>]$/; if(searchCriteria.firstNa ...

Ensure exclusive access to variables for sequential updates in jQuery or JavaScript

I am currently developing a series of small functions in jQuery aimed at tracking how long it takes for a user to complete a form. The form consists of various input types and 'continue' buttons located within the form itself. Below are some sa ...

Hiding javascript code within comment tags "<!-- //-->"

Years ago, I started a practice of enclosing all my JavaScript code in files with <!-- Code goes here //--> I'm not entirely sure why I did this. Maybe it was to hide the code from old browsers, is that right? Do I still need to do this? I ...

When trying to pass context to the interactive node shell, an error message may appear stating "TypeError: sandbox argument must be converted to a context"

I am trying to initiate an interactive node shell with pre-initialized objects. But when I use the code below, it gives me an error: var repl = require('repl') var x = 11, y = 21 var con = {} con.x = x con.y = y repl.start('> &apo ...

Local Passport Authentication

Recently, I delved into the world of JavaScript and embarked on a small project involving user authentication. To achieve this, I decided to utilize the Passport local strategy. However, upon sending a post request with the login button, I encountered an e ...

Sending form data without interrupting the user interface by using asynchronous submission

Using jQuery version 1.7.2, I am currently using the submit() method to send a form via POST. This triggers a Python cgi-bin script that performs some tasks which may take around ten seconds to finish. Upon completion of the task, the Python script instruc ...

React modal not triggered on click event

As a newcomer to react, I am exploring a modal component import React, { useState, useEffect } from 'react'; import { Modal, Button } from "react-bootstrap"; function TaskModal(props) { return ( <Modal show={pro ...