Modify the directive when the scope variable undergoes changes

Utilizing an http request, I am retrieving data from a json file that I then utilize in my controller.

    app.controller('mainCtrl', ['$scope', 'loaderService', function ($scope, loaderService) {
   //Getting data from the service
        loaderService.getLoadedHtml().then(function (result) {
            $scope.fields = result.data;
        });
    }]);

I am interested in updating a directive whenever $scope.fields changes such as:

app.directive('dform', function () {
    return {
        scope: {
            action: '@',
            method: '@',
            html: '='
        },
        link: function (scope, elm, attrs) {
            var config = {
                "html": scope.fields
            };

            scope.$watch('fields', function (val) {
                elm.dform(config);
            });

            //console.log(config);
            //elm.dform(config);
        }
    };
})

Here is how I implement this directive:

<div html="fields" dform></div>

However, when $scope.fields changes in my case, I receive scope as undefined in my directive's $watch function.

Query:

Is there a way to obtain the updated value for scope.fields in the scope.$watch function?

Answer №1

To enable the directive to access fields, you must include a binding for it:

scope: {
  action: '@',
  method: '@',
  html: '=',
  fields: '='
}

Include this HTML code:

<dform fields="fields" ...

If the value is initially undefined, refrain from calling dform:

scope.$watch('fields', function(newValue, oldValue) {

  if (newValue === oldValue) return;

  var config = {
    "html": newValue
  };

  elm.dform(config);
});

Update

When using this HTML snippet:

<div html="fields" dform></div>

You only need to watch html, no additional requirement for $parent or adding fields as a binding:

scope.$watch('html', ...

Answer №2

Typically, directives that aim for maximum transparency should avoid using a new scope. Introducing a new scope can also hinder other directives from requesting their own scopes on the same element.

If only one attribute needs to be dynamic, the solution is straightforward:

scope: false,
link: function (scope, elm, attrs) {
    scope.$watch(function () { return scope[attrs.html] }, function (val) {
        if (val === undefined) return;

        var config = {
            action: attrs.action,
            method: attrs.method,
            html: val
        };

        elm.dform(config);
    });

}

Alternatively, bindToController allows for a more forward-thinking approach (potentially transitioning from $scope.$watch to self.$onChanges as needed).

scope: true,
bindToController: {
    action: '@',
    method: '@',
    html: '='
},
controller: function ($scope, $element) {
    var self = this;

    $scope.$watch(function () { return self.html }, function (val) {
        if (val === undefined) return;

        var config = {
            action: attrs.action,
            method: attrs.method,
            html: val
        };

        $element.dform(config);
    });
}

Assuming html="fields", the provided code will monitor changes in the fields scope property.

Answer №3

try using $parent.fields in place of just fields

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

Steps for adjusting the position of this div in relation to the main container

Apologies in advance for my lack of HTML skills. I am struggling with a page layout issue. I have a website at . When the window is resized, the ads div on the right side overlaps the main container. What I would like to achieve is to make this ads div re ...

troubles with variables in AngularJS Formly templates

Having trouble displaying model or other variables in my template? Check out this link for reference: http://jsbin.com/wofulinufo/edit?html,js,output. Question: What is the solution for displaying variables from controller? Even when I try using {{model} ...

Vue-router is displaying only the root route

I've been working on vue-router for some time now, but I seem to have hit a roadblock. Despite going through numerous articles and documentation, I can't seem to find the solution. Even after reading multiple tutorials on using vue-router, I&apo ...

Creating an overlay with CSS hover on a separate element and the ::before pseudo class

Issue: I am struggling to display the overlay when hovering over the circle element, rather than just the image itself. I have attempted to achieve this using CSS, but can't seem to make it work as intended. Any guidance and examples using JavaScript ...

Shifting the final child to the front position proves unsuccessful with jQuery

I have attempted to move the last element in my list to the first position upon clicking, but unfortunately, it is not working as expected. I followed the advice provided in response to a question on the following page: Move last child to first position. W ...

Accessing a specific child div within a parent div using JavaScript and CSS

Struggling to target and modify the style of the child div within id="videoContainer" <div id="videoContainer"> <div style="width: 640px; height: 360px"> <------- this is the target <video src ...

Issue with swal() not triggering in Internet Explorer 11

Looking for some assistance here, I believe I might be missing a small detail. The _layout.cshtml file includes all the necessary scripts to ensure that sweetheart works on IE: (this used to work in previous versions, but we haven't had to support I ...

Implementing user profile picture display in express.js: A step-by-step guide

I'm having trouble displaying the profile picture uploaded by users or employees in my application. Although the picture uploads successfully, it doesn't show up and gives an error when I try to redirect to the page. Cannot read property &ap ...

What is the best method for tracking the execution time of functions in Node.js?

My nodejs application has numerous functions that need to be executed. I am looking for a way to log the time taken to execute each function. For example, when my app runs these functions: execfn1(); -> should output in some log, takes: 1ms.. execfn ...

Tips for keeping notification icons in the upper right corner of the box?

I am facing an issue with absolute positioning where the notification icons I've positioned to the top-right corner of a box are moving away when the screen size changes. Desired appearance of the image Actual appearance when screen size is adjusted ...

The Angular JS Factory fails to send data back to the controller

When I call the method getPopularMovies in my factory using the controller, it returns undefined. I'm not sure what mistake I've made here. Please help me figure it out. My Factory angular.module('ngMovies').factory('moviesFactor ...

How can we effectively streamline these if statements for better organization and efficiency?

Currently, I am dealing with a straightforward if condition structure and aiming to keep the code as DRY (Don't Repeat Yourself) as possible. I believe that I have achieved optimal dryness for my specific situation by utilizing object keys as pointers ...

Exploring React: Opening a new page without rendering the SideBar component

I currently have an application with a sidebar that navigates to three different pages, all of which include a navigation bar and the sidebar. However, for the next page I want to exclude the sidebar but still include the navigation bar. How can I configur ...

Employing Jquery for restricting checkbox selection based on parent HTML elements

UPDATE I am looking to limit checkbox selection in specific sections on the same page. To prevent conflicting inputs from different sections, I believe using the label selector <label data-addon-name="xxx"> as a separator is the best appro ...

unable to display data through the web service

The functionality of this code is correct, but it seems to not be displaying records. When the record is retrieved from the file and shown in an alert, everything works fine. $j().ready(function(){ var result =$j.ajax({ ...

Searching by multiple parameters in Angular.js

I have a script that scans through a field and highlights the words related to the search input. I want this script to not only filter by title, but also by name. How can I adjust the code to filter both the title and name when searching? <li ng-repeat ...

"Learn how to use socket.io in conjunction with the express generator to create individual sockets for each unique link

I'm working on a typical express-generator app where I have some code in my controllers folder: router.get('/:id([A-Za-z0-9_]{5,25})', function(req, res, next) { res.render('my-page.html', { title: 'Messag ...

Can pagination numbers in Jquery DataTable be configured based on the total records returned by the server and the number of records chosen by the user?

I am currently diving into the world of DataTable.js, a jQuery plugin, and working hard to articulate my questions effectively. For my specific needs, I need to retrieve only 10 records initially whenever an AJAX request is made, even if there are 100 rec ...

Executing SQL queries in JavaScript using PHP functions

Is it allowed, or is it a good practice? It worked for me, but what issues might I face in the future? Just to clarify, I am new to PHP scripting. // button <button type="button" class="btn btn-primary" id="Submit-button" >Save changes</button> ...

problem with running a node server on localhost

I've been attempting to test a simple Javascript file, but I'm encountering difficulties. When I try to load the page in my browser, it seems to be stuck loading forever with no warnings. At the bottom of the page, a text bar appears stating "wai ...