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

What are some ways to customize the appearance of the Material UI table header?

How can I customize the appearance of Material's UI table header? Perhaps by adding classes using useStyle. <TableHead > <TableRow > <TableCell hover>Dessert (100g serving)</TableCell> ...

Challenges arise when attempting to authenticate a user with password.js

Currently, I am working on implementing validation using passport.js and ES6. Below is the validation function that I have created: passport.use(new BasicStrategy( function(login, password, callback) { User.findOne({ login: login }).select(&a ...

When using element(by.binding('...'),getText(), all the content within the element is retrieved, as opposed to just the element itself

Examining the outcome of {{price}} and {{getAdditionalKm}} in my AngularJS Application using Protractor. Here is a snippet of the HTML I aim to test: <h1>{{ price(distance, time, time_standing, airport) | currency }}</h1> <p>Detailed Pr ...

Auto-filling a form with the selected 'id' in Django using JavaScript or AJAX

I am a novice and I want the form to be autofilled when I select a vehicle ID from the template. Here are my models. class Fuel(models.Model): vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) previous_km = models.IntegerField(blank=False, nul ...

What could be causing my node.js to fail in producing a true result within the return statement?

I've encountered an issue with VS code where the return true command is not displaying anything in my terminal, while console.log(map[arr2[j]]) successfully returns true. I'm unsure if this problem lies with node or my terminal. How can I ensure ...

Adjusting the overflow of a parent div based on the position of the div within it by scrolling

I'm trying to create a page with 3 different sections: <div class="container" id="main-container"> <div class="section" id="profile"> Hello World </div> <div class="section" id="projects"> Hello World 2 ...

Executing a Node.js script using an absolute path

In the process of developing a basic app using Node.js and Express, I've encountered an issue. The script is located at path/to/script/server.js. When I run this script with node server.js while in the correct directory, everything functions correctly ...

The deployment of my Node application on Heroku is causing an error message: node-waf is not

I've been trying to deploy my Node.js application on Heroku by linking it to my Github repository and deploying the master branch. Despite experimenting with various methods, I keep encountering the same error every time. You can view the detailed b ...

What sets these async method declarations apart?

What goes on behind the scenes? const facade = { // A: doSomething: async () => await delegatedFunction(), // B: doSomething: async () => delegatedFunction(), // C: doSomething: () => delegatedFunction(), // D: do ...

A guide on extracting specific text from a div class

<div class="col_5"> <br> <i class="phone"> :: Before </i> 0212 / 897645 <br> <i class="print"> ...

Where do I find the resultant value following the completion of a video production through editly?

Hey there, I have a quick question... I was following the instructions in the README for editly, and I successfully created videos by calling editly like this: // creating video editly(editSpec) .catch(console.error); The only issue is that I am using Ex ...

Issue occurred when trying to load controllers during the migration process from AngularJS1 to Angular6

Currently, I am in the process of upgrading AngularJS1 components to Angular6. My strategy involves creating wrappers for all existing AngularJS1 components by extending "UpgradeComponent" and storing them under the folder "directive-wrappers". However, wh ...

"Creating dynamic web apps with the powerful duo of Meteor and Zurb

Just starting out with programming and currently working on a new web application using Meteor and AngularJS. I would like to incorporate the elements/css from 'Zurb Foundation For Apps' into my project... I am familiar with including Bootstrap ...

Can a JavaScript function be sent through a REST API using Node.js and Express?

I have a unique scenario where I need to send a custom JavaScript function as a response to a GET request made to an API endpoint. Currently, I am using Node.js with Express for my server implementation, but I am open to exploring other frameworks. When a ...

"Upon the second click, the Ajax success function will display the returned view

When using a post request in angular's factory with ajax, everything seems to be working fine except for the success function. Upon clicking the login button, it seems like I have to click it twice to navigate to another page (logout.html). I'm n ...

The Vue.js modal is unable to resize below the width of its containing element

My challenge is to implement the Vue.js modal example in a larger size. I adjusted the "modal-container" class to be 500px wide, with 30px padding and a max-width of 80%. However, I'm facing an issue where the "modal-mask" class, containing the contai ...

Is there a way to access comprehensive data pertaining to an ID through Ajax?

I need help with an Ajax call. Below is the code I currently have: $.ajax({ async: true, url: 'test/', type: 'POST', datatype: 'text json', data: { id: id, }, success: function(data) { // Retrieve the da ...

Prevent running function bodies simultaneously based on user events in JavaScript until a previously triggered execution is completed

When a user clicks on a button in my component, the doSomething function is activated. The issue I am facing is that doSomething takes between 200-1100ms to finish execution and change state. What complicates matters is that when the button is clicked rapi ...

Embed a function within a string literal and pass it to another component

Is there a way to pass a function defined in actions to an element? Reducer case 'UPDATE_HEADER': return Object.assign({}, state, { headerChildren: state.headerChildren.concat([action.child]) }); Action.js export const deleteH ...

There is no way to avoid a PHP variable being displayed in a JavaScript alert box

It may sound silly, but I've spent hours trying to escape this PHP variable that contains post data: $post=array ( 'offers' => '90', 'pn' => '2', 'ord' => 'price', 'category_s ...