Adjust the user interface in response to a modification in a directive attribute within AngularJs

I am currently facing challenges with data binding in AngularJs.

Within my .html file, I have the following markup that includes a custom directive:

<my-directive ng-repeat="i in object" attr-1="{{i.some_variable}}"></my-directive>

Important Note: The 'some-variable' value is updated every 10 seconds (based on the associated collection and passed to the template through the controller).

The code for the directive is as follows:

myApp.directive('myDirective', function () {

  scope: {
   'attr-1': '=attr1'

This results in an exception due to the brackets in attr-1 as shown in the html code above.

However, it functions correctly when using read-only access (noted with the at-sign below):

myApp.directive('myDirective', function () {

  scope: {
   'attr-1': '@attr1'

I utilize scope.attr-1 in the directive's HTML to display its value.

The issue lies in the fact that with read-only access, the UI fails to reflect any changes made to the attribute.

I came across a potential solution involving $parse or $eval, but I struggled to implement them. Are there better alternatives available?

Answer №1

Only utilizing two-way binding is necessary, without the need for $parse or $eval.

Take a look at the demonstration below or in this interactive demo.

This example utilizes $interval to mimic updates, but data can also be updated from various sources like web sockets or ajax requests.

I'm employing the controllerAs and bindToController syntax (requires AngularJS version 1.4 or newer), although using an isolated scope is also possible. Refer to the Angular documentation for more details.

The $watch function in the directive's controller is simply demonstrating how the directive can detect changes in the data.

angular.module('demoApp', [])
.controller('MainController', MainController)
.directive('myDirective', myDirective);

function MainController($interval) {
var self = this,
        refreshTime = 1000; //interval time in ms
    
    activate();
    
    function activate() {
    this.data = 0;
    $interval(updateView, refreshTime);
    }
    
    function updateView() {
    self.data = Math.round(Math.random()*100, 0);
    }
}

function myDirective() {
return {
    restrict: 'E',
        scope: {
        },
        bindToController: {
            data: '='
        },
        template: '<div><p>directive data: {{directiveCtrl.data}}</p></div>',
        controller: function($scope) {
            $scope.$watch('directiveCtrl.data', function(newValue) {
            console.log('data changed', newValue);
            });
        },
        controllerAs: 'directiveCtrl'
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js"></script>
<div ng-app="demoApp" ng-controller="MainController as ctrl">
    model value in ctrl. {{ctrl.data}}
    <my-directive data="ctrl.data"></my-directive>
</div>

Answer №2

Here is the approach I implemented (in case someone encounters a similar issue):

// Custom Directive Implementation

myApp.directive('customDirective', function () { return {
    restrict: 'E',

    templateUrl: function () {
        return 'custom-directive.html';
    },
    scope: {
        'id': '@attrId',
        'x': '@attrX',
        'y': '@attY',
        //....
    },
    link: function ($scope, element, attrs) {

         // *** CUSTOM SOLUTION ***
         attrs.$observe('attrId', function (id) {
             $scope.id = id;
         });
         //...
    }

Update: I received an answer from someone facing a similar challenge, and they devised a solution that closely resembles mine:

Dealing with directive inside ng-repeat and magic of scope '@'

This reference provides insightful explanations behind the concept.

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

Make a diagonal border using CSS styling

Is it possible to create a slanted border like the one shown in this image (red line) using CSS/CSS3 or JavaScript? <div id="DIV_1"> <img src="/uploads/2016/01/logo.jpg" width="250px" id="IMG_2" alt='' /> <nav id="NAV_3"& ...

Prompt for confirmation in ASP.NET code-behind with conditions

I've searched around for a solution to this problem. Below is a representation of my pseudocode: bool hasData = ItemHasData(itemid); Confirm = "false"; // hidden variable if (hasData) { //Code to call confirm(message) returns "true" or "false" ...

The dynamic data is not displaying on the Chart bundle JavaScript

I am currently utilizing chart bundle js for my project. While everything appears to be functioning properly on alter show, I am encountering an issue with the map display – nothing is showing up as intended. If anyone has a solution to resolve this iss ...

Establish the dimensions of the element to match the dimensions of a responsive image

Currently, I am working on implementing flippable images on my website. It is important to me that the "back" of these images matches the dimensions of the front image. The challenge I am facing is that I have applied the Bootstrap img-responsive class to ...

Google is currently unable to provide the accurate latitude and longitude of the current position

I'm looking to incorporate geolocation functionality into my Laravel project. I've implemented this code, but it seems to be giving me slightly different latitude and longitude values. function getLocation() { var x = document.getElementById( ...

What is the best way to transfer a value from my HTML into a directive component?

Looking for a way to retrieve a value within a directive: app.directive('testDir', [function () { return { require: '?ngModel', link: function ($scope, elm, attr, ngModel) { var abc=<some string passe ...

Generating HTML content using JavaScript object data

I have a JavaScript file that holds data in the form of objects : let restaurant_A = { name: "BBQ place", min_order: 20, delivery_charge: 5, menu: { //First category "Appetizers": { //First it ...

Navigating through Sails.js: A comprehensive guide on executing test cases

Being a beginner in sails, node, and js, I may be missing out on some obvious steps. My environment includes sails 0.10.5 and node 0.10.33. Although the sails.js documentation covers tests in , it does not provide instructions on how to actually execute ...

Guide on how to trigger the opening of a side panel with a button click in Vue.js

Embarking on my first Vue app development journey, I find myself in need of guidance on how to trigger the opening of a panel by clicking a button within the header. Starting off with a simple HTML template, my goal is to add some interactivity upon click ...

Discovering the nearest sibling using jQuery

My HTML code snippet is as follows: $(".remove-post").click((event) => { $(event.target).fadeOut(); } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="side-bar"> <b ...

"Implementing conditional rendering to hide the Footer component on specific pages in a React application

Is there a way to conceal the footer component on specific pages? app.js <div className="App"> <Header setShowMenu={setShowMenu} /> {showMenu ? <Menu navigateTo={navigateTo} setShowMenu={setShowMenu} /> : null} <Main na ...

Exploring Partial Views in Bootstrap Single Page View and AngularJS

Currently, I am utilizing Bootstrap's single page view design, specifically the one found at this link: http://www.bootply.com/85746. As my code in the view has grown to nearly 500 lines and is expected to expand further, I am seeking a method to crea ...

What is the method for accessing the Redux store content directly in the console, without using any developer tools

By utilizing React Devtools, I am able to access the store by: $r.store.getState() Is there an alternate method to retrieve the store without using React Devtools? ...

Using Node.js setTimeout method

I'm struggling with understanding how to utilize the setTimeOut function in NodeJS. Let's say I need: function A() to be executed every 10 seconds. If function A returns 'true' from its callback, it should trigger a call to a specific ...

Discovering the point of exit for a mouse from an image

Visit this website to see the effect in action: I am curious about how the image scrolls into and out of the direction where the mouse enters and leaves. Can you explain how this is achieved? ...

Is it possible to convert a jQuery function into an AngularJS directive?

I am currently working on implementing form validation in AngularJS using a directive to enable or disable the submit button based on the form's validity. Although I have a jQuery function that performs input comparison to prevent duplicate informati ...

I must determine whether the contents of an array exceed zero

THE SUMMARY: I have three value numbers for an array. If the total addition of the array's elements is greater than 0, I need to display "el funcionamiento no es infinito", otherwise "es infinito". It seems that it's not working because I belie ...

Function for JavaScript Form Validation: Iterating through each element

I have a set of form input elements that need to be iterated through in order to validate them based on their name attributes. I utilized jQuery to accomplish this, using the .each method to loop through the elements and apply/remove a class name to those ...

Next.js fails to load TailwindCSS

I am in the process of developing an app using tailwindcss and next.js First, I started creating the nextjs app, then I executed these commands: npm install -D tailwindcss postcss autoprefixer npx tailwindcss init -p Following that, I made adjustments t ...

The Alertify dialog vanished without being able to confirm

While working on some code, I encountered a specific issue: alertify.dialog("confirm").set( { 'labels': { ok: 'Personal', cancel: 'Share' }, 'message': 'Select target:', ...