Monitoring $scope modifications within a directive: A simple guide

I am currently working with a directive that looks like this:

app.directive('selectedForm', function(MainService) {
    return {
        scope: {
            formName: '=currentForm'
        },
        restrict: 'E', 
        link: function($scope, iElm, iAttrs, controller) {
            $scope.$watch('formName', function(oldV, newV) {
                console.log(iElm);
                if (someCondition) {
                    MainService.getForm($scope.formName).then(function(re) {
                        iElm.html(re);
                    });
                }
            });
        }
    };
});

Unfortunately, I have encountered an issue where I am unable to watch for changes. I have a <select> element in the DOM that updates the value of currentForm using ngModel. However, even after selecting an option, the watch function does not seem to work correctly. Am I overlooking something important here?

Answer №1

When using the $watch function in an angular directive, it cannot be executed in the same manner as you would in an angular controller. To make it work, adjust your code to look like this:

Modify your html select element as follows:

<select model="selectedElements">
    ...
    ...
</select>

Within your directive, update the $watch section to:

...
link: function($scope, iElm, iAttrs, controller) {
            $scope.$watch('iAttrs.model', function(oldV, newV) {
...

For more information, check out this link: Is it ok watch the scope inside a custom directive?


EDIT:

To watch the value of

<select ng-model='currentForm'> ... </select>
, use the following code snippet:

...
link: function($scope, iElm, iAttrs, controller) {
            $scope.$watch('iAttrs.currentForm', function(oldV, newV) {
...

EDIT 2

Latest updates based on feedback received:

In your html

<selected-form ng-model="currentForm"></selectedForm>

and in your controller

...
link: function($scope, iElm, iAttrs, controller) {
            $scope.$watch('iAttrs.ngModel', function(oldV, newV) {
...

EDIT 3

Check out the updated plunker here:

https://plnkr.co/edit/v5EnmpQ9UtApnM5ErnYi?p=preview

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

The bootstrap navbar dropdown feature isn't functioning properly on iPhones

Currently utilizing "bootstrap": "~3.3.4" within the mean.js framework, I am facing an issue with the navbar dropdown menu. On desktop, everything functions as expected - the dropdown opens and remains open when the icon is clicked. However, once deployed ...

Being required to design a distinct div for every article I am extracting from the API

In the midst of developing a website for my college project, I have successfully configured my news API to pull and display data using JavaScript. Currently, I am faced with the challenge of having to create separate div elements each time I want to add n ...

Can Socket.IO link to a source tag that doesn't actually exist?

As I was following the 'Get started thing' tutorial on Socket.IO, I encountered a step that required me to add the socket.io.js script to my HTML page. The instruction provided was: /socket.io/socket.io.js However, when I checked my folders, I ...

Run the function multiple times by substituting a portion of the argument in a sequential

I am facing a challenge with a method (exampleObj.method) that requires arguments of an object and a function. The code snippet is as follows: exampleObj.method({ name1: 'string1', name2: 'string2', name3: &apos ...

Save to a JSON file

Hey there, I'm having some trouble with pushing a temporary value to a JSON file using the command "MyJSON.name.push". It keeps giving me an error saying "Undefined is not an object". I've tried different approaches and using JavaScript arrays wo ...

The "events" module could not be resolved in React-Native

The server encountered an internal error: 500 URL: Body: {"message":"There was an issue resolving the module events from the specified directory. This may be due to a module not existing in the module map or directories listed.","name":"UnableToResolveEr ...

Error: Axios header not refreshing automatically in React. User must manually refresh the page

After logging in, I want to update the JWT token in the header before redirecting to the home page. Login.tsx ... const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => { event.preventDefault(); const data = new FormData(event.curr ...

The Implementation of Comet Programming

I'm interested in creating a web application similar to Google Docs where multiple users can edit and view changes in real-time. Would Comet Programming be the best approach for this? As a newcomer to Web Development, I'm currently learning Java ...

What is the best way to achieve a Clamp-To-Border effect on a Texture loaded onto an Image in the THREE.js?

My scene includes a plane with an image loaded onto the texture. I've found that there is no Clamp-To-Border option for textures, only Clamp-To-Edge, Repeat Wrapping, and Mirrored Wrapping. Below is an image displaying the default ClampToEdge effect. ...

Invoke a JavaScript function with arguments upon clicking on a hyperlink

Struggling to generate code for an href tag with a JavaScript function that takes parameters - a string and an object converted into a json string. My initial attempt looked like this: return '<a style="text-decoration:underline;cursor:pointer" ta ...

How do I combine Firefox binary specification with adding the Firebug extension when using Selenium?

Presently I am utilizing the code below. var co = require('co'); var WebDriver = require('selenium-webdriver'); var SeleniumServer = require('selenium-webdriver/remote').SeleniumServer; co(function *() { // async var ser ...

inject the HTML content into the <div> container

Snippet: https://jsfiddle.net/x9ghz1ko/ (Includes notes.) In my HTML file, there are two distinct sections: <section class="desktop_only"> and <section class="mobile_only">. The challenge lies in positioning a JavaScript sc ...

Checking the alignment of a label or element in the center of a webpage using javascript

I am new to JavaScript and was attempting to determine if an element is centered aligned by accessing its CSS properties/values. Can someone help me retrieve the CSS property to verify text alignment using JavaScript? ...

Incorporate numerous style classes into an object using React Material-UI

I am facing an issue with my JSX code: <span className="btn-pause btn"><i class="fa fa-pause"></i></span> I would like to change the color of this button. Here is what I have tried: const styles = { btncolor ...

The blur event is failing to trigger in my custom input component

// The Custom Input component const Box = styled.div``; const InputBox = styled.div<{ width: string }>` display: flex; width: ${(props) => props.width}; height: 42px; justify-content: space-between; align-items: center; padding: 9px ...

Steps to resolve the issue: The 'jsx' functionality is not activated at the moment

I recently started working with ReactJS and I came across a similar error message in this post: Syntax Error: Support for the experimental syntax 'jsx' isn't currently enabled. Despite reading it, I am still unable to solve my issue. When I ...

The Cordova File Transfer component decodes the encoded URL

Currently, I am in the process of developing an Ionic application and utilizing Cordova file transfer to download specific video files. Download URL : https://*****/*-52e10254-85c5-459c-98f3-5c5fe89e3326/deb5bcc6-2767-4b45-b57f-94bacd4b_960x540_1500.mp4?s ...

jQuery: changing the order of list elements with the eq method

I've been tackling a challenge with designing a navigation bar that consists of 3 items. The goal is to have the clicked item move to the center position on the horizontal navbar while re-arranging the order. Here's the code snippet I've com ...

Delaying UI interactivity until the document is fully loaded

I'm currently developing a web application that must be compatible with Internet Explorer 8 (yes, you read it right, compatible with the HELL). The issue I'm facing is with uploading a file which is later processed by PHP code and then refreshes ...

Using Vue's v-bind directive with a single set of curly braces expression

Currently, I am delving into the world of Vue.js to broaden my knowledge and gain practical experience. While following a tutorial, I encountered an interesting scenario involving the addition of a class to a span element based on a condition within a v-f ...