Observing the Result of a Function within a Controller Using Ng-Repeat in a Directive

I'm struggling with making a custom directive watch the result of a function that's bound to the scope in the controller.

Here is the HTML. I'm passing the key of the ng-repeat to the function in the controller in order to determine whether this element should be active or not.

<div ng-repeat="(key, value) in myArray" my-custom-directive element-is-active="elementIsActive(key)">
</div>

This is the part of the code in the controller that matters. Depending on the user's input, this function returns either true or false, indicating whether the element is selected or not.

$scope.elementIsActive = function (key) {
    if(key===$scope.selectedElement) {
        return true;
    }
    return false;
}

If the element is active, I want the custom directive to perform its functionality. Here's the custom directive:

myAngularModule.directive('myCustomDirective', function (){

    function link (scope, element, attrs)  {

        scope.$watch(scope.active(), function (){
            console.log("triggered");
        });

    }

    return {
        link:link,
        scope: {
            active: "&elementIsActive"
        }
    }

})

I am encountering difficulties getting the $watch method to work properly. The message "triggered" appears only once upon loading, and then it seems to stop watching, despite the fact that the output of the function is changing.

Answer №1

To keep an eye on a specific attribute within the scope, simply follow these steps:

scope.$watch('active', function (){

Since you are already utilizing the function in

element-is-active="elementIsActive(key)"
, you can directly access its return value as a standard variable in your scope:

return {
    link:link,
    scope: {
        active: "=elementIsActive"
    }
}

For further reference, check out this plunker.

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 implement React Router within an if/else statement inside a function triggered by a button click?

const handleStartClick = () => { const userEmail = localStorage.getItem('email') if (userEmail !== null && userEmail.length !== 0) { alert('The email is not empty!') } else { <Routes> ...

Iterate through the .json file and add markers to a leaflet map

Apologies for the basic question, but I'm struggling with understanding JavaScript and json files. I have a .json file that updates server object locations every 5 seconds, and I want to plot these coordinates on a map using leaflet for staff access. ...

Tips for automatically resizing a canvas to fit the content within a scrollable container?

I have integrated PDF JS into my Vue3 project to overlay a <canvas id="draw_canvas"> on the rendered pdf document. This allows me to draw rectangles programmatically over the pdf, serving as markers for specific areas. The rendering proces ...

Ways to deactivate a button with a designated identification through iteration using jQuery

Can't Figure out How to Deactivate a Button with Specific ID $('.likes-button').click(function(){ var el= this; var button1 = $(el).attr('id'); console.log(button1) $('#button1').attr("disabled",true); }) ...

Probability of an event occurring when represented as whole numbers in percentage form

Currently, I'm developing a unique job system within a Discord bot that allows users to mine various types of ores. The probability of receiving specific ores is based on the user's mining skill level, which is stored in a database and can vary a ...

What is the most efficient way to retrieve the operating system's name and version using JavaScript?

I'm in the process of developing an object that will simplify accessing browser and system information by implementing a function. One particular function within this object is responsible for retrieving the operating system name and version, returnin ...

When a function encounters an error, load a fresh page

I am facing an issue where I want to display a new error page whenever a function throws an error. The current situation is that when the getStockPoints function encounters an error and I handle it using try and catch block in app.js, the error is caught b ...

What is the best way to invoke the first exported function from the second exported function?

I am looking to create a file containing four or five exported functions. exports.firstFunction = function() { // some code }; exports.secondFunction = function() { // need to call firstFunction }; My issue is that I want the second expo ...

Transforming an array into key-value pairs where the keys are odd elements and the values are even elements

Is there a straightforward way to transform this initial array: [ "Bargain", "deal", "Consistent", "Steady; regular", "Accurately", "a thing bought or offered for sale much more cheaply than is usual or expected.", "Charge", "demand (an am ...

When utilizing Express, only the index.html page is rendered, all additional pages

I've set up an express app specifically for serving static HTML files. let express = require('express'); let path = require('path'); let cookieParser = require('cookie-parser'); let logger = require('morgan'); ...

Sending a file to a node.js server via a bootstrap/angular template on an ejs webpage

Today marks my third day trying to crack this code, so I've decided to seek some assistance. I'm attempting to enable file uploads with searchable filenames or keywords for future reference. The idea is to store them in a dataset so that I can e ...

Screenshots of playwright failing to work on Github.''

Within my playwright.config.ts file, I have specified the following: use: { ... screenshot: 'only-on-failure', } When running tests locally and they fail, screenshots are successfully saved in /test-results. However, the issue arises when th ...

An Ajax call navigates to the index.html page

Could you please assist with an issue I am facing? I have written the code below to make an ajax request to a specific link. However, instead of executing the ajax call using a POST request, the page is being redirected to index.html with the link in the ...

A guide on clearing the selected value in a dropdown menu with Angular.js

Can someone assist me with setting the drop-down value to blank after completing an action in Angular.js? Below is my code explanation: <div style="height:270px; overflow-x:hidden; overflow-y:scroll;" ng-show="viewOrderTable"> <div class="table-r ...

How to create a responsive image that appears over a button when hovering in Bootstrap?

My goal is to display an image over a button when hovering. I've tried adding the .img-responsive class in Bootstrap while including the image in the HTML, but it's not working as expected with my current method of loading images. The buttons the ...

Create a custom Angular directive that allows you to replace tags while inserting the template

I have created a custom directive that can take templates based on the attribute provided. Check out the Plnkr example JS var app = angular.module('app', []); app.directive('sample', function($compile){ var template1 = '<d ...

When trying to access localhost:5000, the index.js file is unable to retrieve /

const NutritionAPI = require('./nutritionapi'); const nutService = new NutritionAPI('50cee42503b74b4693e3dc6fccff8725','2755697297a84ac5a702461b166e71f6'); // Setting up Express webhook const express = require('express&ap ...

adding a touch of flair to a form input that doesn't quite meet the

My goal is to have a red background appear when an input is invalid upon form submission. I attempted the following code: input:invalid { background-color:red; } While this solution worked, it caused the red background to show up as soon as the page l ...

How can you add draggable functionality to a Bootstrap dropdown menu?

My custom bootstrap dropdown design <div class="dropdown"> <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"> Dropdown <span cla ...

Exploring Various Shapes in THREE JS

Currently, I am utilizing the EdgesGeometry for rendering my objects. I am currently exploring options on how to morph a Tetrahedron into an Octahedron, an Octahedron into a Box, a Box into a Sphere, and vice versa. Despite searching through numerous doc ...