What is the best way to detect modifications to scope variables within a directive?

Here are some instructions for HTML:

<dropdown placeholder='' list='sizeWeightPriceArr' selected='selectedProductSize' property='size' value='size' style='width:60px;'></dropdown>

The variable selectedProductSize is a scope variable. The basic concept is that when a value is selected in the dropdown, this variable in the selected attribute saves all the changes. JavaScript:

.directive('dropdown', ['$rootScope', function($rootScope) {
    return {
        restrict: "E",
        templateUrl: "templates/dropdown.html",
        scope: {
            placeholder: "@",
            list: "=",
            selected: "=",
            property: "@",
            value: "@"
        },
        link: function(scope, elem, attr) {
            scope.listVisible = false;
            scope.isPlaceholder = true;

            scope.select = function(item) {
                scope.isPlaceholder = false;
                scope.selected = item[scope.value];
                scope.listVisible = false;

            };

            scope.isSelected = function(item) {                                                                                      
                return item[scope.value] === scope.selected;
            };

            scope.show = function() {
                scope.listVisible = true;
            };

            $rootScope.$on("documentClicked", function(inner, target) {
                if(!$(target[0]).is(".dropdown-display.clicked") && !$(target[0]).parents(".dropdown-display.clicked").length > 0) {
                    scope.$apply(function() {
                        scope.listVisible = false;
                    });
                }
            });                     

            scope.$watch('selected', function(value) {
                if(scope.list != undefined) {
                    angular.forEach(scope.list, function(objItem) {
                        if(objItem[scope.value] == scope.selected) {
                            scope.isPlaceholder = objItem[scope.property] === undefined;
                            scope.display = objItem[scope.property];
                        }
                    });
                }
            });

            scope.$watch('list', function(value) {
                angular.forEach(scope.list, function(objItem) {
                    if(objItem[scope.value] == scope.selected) {
                        scope.isPlaceholder = objItem[scope.property] === undefined;
                        scope.display = objItem[scope.property];
                    }
                });
            });

        }
    }
}])

The dropdown.html file is not relevant. When a selection is made, the scope.select function runs inside the directive, setting the selected value in

scope.selected = item[scope.value];
which works. In the controller, I tried to use $scope.$watch to capture changes and trigger a function, but it did not work:

$scope.selectedProductSize = '';
$scope.$watch('selectedProductSize', function(value) {
    ...                     
});

Answer №1

Instead of using $watch, you can achieve two-way data binding by passing the variable directly to the directive.

In your controller:

$scope.my_var = ''

Directive HTML:

myvar=my_var

Directive:

scope: {
  myvar: '='
}

The $scope.my_var will be synchronized with the directive's myvar. This means that any changes to myvar in the directive will update $scope.my_var in your controller as well.

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

JSON response is not being successfully passed in PHP Ajax form validation

I've been struggling to solve my code for the past few days but haven't had any success. I'm attempting to validate my login form using AJAX, however, it seems like there's an issue with my Jquery AJAX script. Every time I try, the con ...

Running AngularJS controllers should only occur once the initialization process has been fully completed

I am facing a situation where I need to load some essential global data before any controller is triggered in my AngularJS application. This essentially means resolving dependencies on a global level within AngularJS. As an example, let's consider a ...

Obtain one option from the two types included in a TypeScript union type

I am working with a union type that consists of two interfaces, IUserInfosLogin and IUserInfosRegister. The TUserInfos type is defined as the union of these two interfaces. export interface IUserInfosLogin { usernameOrEmail: string; password: string; } ...

Using jQuery and Bootstrap in an ASP.NET Core project

I am encountering an issue with the configuration of bootstrap and jquery within my project, causing these tools to fail to load properly. The problem seems to be that bootstrap is loading before jquery, resulting in error messages appearing when I check ...

Tips for extending the space between one element and another when the width decreases:

Currently in the process of building a website using HTML/CSS/JS and have run into an issue. My front page features an image with text overlay, where the image has 100% width and a fixed height of 487px. I positioned the text using position:relative; and t ...

Steps for generating an observable that mirrors the structure of an observable array

I am in the process of creating an observable array using JSON data retrieved from the server. var ViewModel = function (data) { var self = this; self.list = ko.observableArray(data); self.selected = ko.observable(); } ...

Combine multiple key values from an array of objects into a single array

I have a set of key and value pairs that I need to filter based on whether the values are in an array or not, and then combine them into a single array. const holiday_expenses = { food: [{name: "abc", place: "xyz"}], travel: [{name: ...

Tips for utilizing ion view within an ionic 2 application

In my original use of Ionic 1, I placed the footer after the <ion-content> and before . However, in the new Ionic 2, I can't seem to find any reference to <ion-view>. My specific need is to have two buttons at the bottom of the screen fol ...

Looking for a JavaScript library to display 3D models

I am looking for a JavaScript library that can create 3D geometric shapes and display them within a div. Ideally, I would like the ability to export the shapes as jpg files or similar. Take a look at this example of a 3D cube: 3d cube ...

Broaden material-ui component functionality with forwardRef and typescript

To enhance a material-ui component with typescript, I have the javascript code provided in this link. import Button from "@material-ui/core/Button"; const RegularButton = React.forwardRef((props, ref) => { return ( <B ...

List of characteristics belonging to objects contained within an array

Consider the following array of objects: data = [{x: 1, y: 2, z: 3}, {x: 4, y: 5, z: 6}, {x: 7, y: 8, z: 9}] Is there a way to extract only the x elements from these objects and create an array out of them? For example: x = [1, 4, 7] Can this be achiev ...

Replacing a string using Regular Expression based on certain conditions

When working with a node.js server, I encountered the need to modify URL addresses using JavaScript in a specific way: For instance: hostX/blah/dir1/name/id.js?a=b --> name.hostY/dir2.js?guid=id&a=b Another example: hostZ/dir1/name/id.js --> ...

What is the method for incorporating text into the Forge Viewer using three.js?

Currently, I am attempting to incorporate TextGeometry into the viewer using Three.js. I am curious about the feasibility of this task and the steps to achieve it. After exploring the documentation, I encountered challenges as the Forge viewer operates on ...

Issues with Cross-Origin Resource Sharing (CORS) when integrating Sinatra and Angular

I am encountering challenges with a simple web application. Here are the relevant files: public/index.html <!DOCTYPE html> <html lang="en" data-ng-app> <body> <div data-ng-controller="PlayersCtrl"> <div data-ng-re ...

What could be causing the Vue.js image component to malfunction?

I am having an issue. I want to create a Vue.js Component. This component displays an image, similar to the <img> tag. If you are familiar with the <img> tag, this question should be easy for you to understand. Here is the code I have: props ...

Automate table column width adjustments in HTML using Selenium WebDriver

As of now, I am working on automating the process of increasing the width of an HTML table column using Selenium WebDriver. I discovered that I can retrieve the coordinates of x and y by using findElement(By.cssSelector("<Css locator>").getLocation( ...

Troubleshooting incompatibility issues between Tailwindcss and NextJS 12 due to experimental features

When I first started using NextJS 12, I decided to try building a project with tailwind. This is my package.json file: { "name": "test", "version": "0.1.0", "private": true, "scripts": { ...

Improved explanation of DOM elements in raw JavaScript

Is there a more efficient way to dynamically create this DOM block: <tr> <td>text</td> <td><input type="checkbox"></td> </tr> I have a function that adds a nested tr element to my tbody: function inse ...

Create an input element using JavaScript/jQuery

Looking for some help with Javascript on a simple task. When a specific option is chosen, I want to add an input field to a div element. <select name="amount" > <option value="50">50$</option> <option value="100">100$</o ...

What is the best way to set up v-models for complex arrays or nested objects?

I'm looking to efficiently create multiple v-models for random properties within a deep array, where the position of attributes in arrays/objects can change dynamically. While I've managed to achieve my goal with the current setup, I'll need ...