Identifying and capturing changes in child scope events or properties in Angular

I am encountering an issue with my form directive where I need to intercept ng-click events nested within varying child scopes of the form element. However, I am struggling to hook into these events or child scope properties in a generic way.

For demonstration purposes, you can view a demo here.

html

<body ng-controller="MainCtrl">
    <form my-form-directive>
      <div ng-controller="SubCtrl">
        <a ng-click="changeName()">click me</a>
      </div>
    </form>
  </body>

javascript

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {

});

app.controller('SubCtrl', function($scope) {
  $scope.name = 'John';

  $scope.changeName = function() {
    $scope.name = 'Peter';
  }
});

app.directive('myFormDirective', 
    function() {
      return {
        link: function($scope, element, attrs, controller) {
          // Looking to watch for ng-click or $scope.name changes and log 'Peter' to console
          // Without assuming nested location of element with ng-click (catch all form ng-click events)
        }
      };
    }
  );

Any assistance would be greatly appreciated. Thank you.

Answer №1

To successfully implement this solution, a few steps need to be taken

Initially, jQuery was incorporated to utilize the find function.

Subsequently, the directive must be relocated within the SubCtrl controller.

HTML

<body ng-controller="MainCtrl">
  <div ng-controller="SubCtrl">
    <form my-form-directive name="name">
      <a ng-click="changeName()">click me</a>
    </form>
  </div>
</body>

Include a scope parameter name in the directive

HTML

 <form my-form-directive name="name">

JS

 scope: { name: '=' },

Finally, within the directive, monitor all elements with ng-click and trigger a click event upon clicking.

JS

element.find('[ng-click]').on('click', function(){
  console.log($scope.name);
});

Example: http://plnkr.co/edit/7lVWjjT2mssmcBD7uP1Z?p=preview

If desiring a purely angular solution, a watch can be added to the directive's $scope.name

JS

$scope.$watch(
  function(){ return $scope.name; }, 
  function(){ console.log($scope.name); }
);

Example: http://plnkr.co/edit/JG21UvdfBfDoMkCRWKqD?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

Overuse of jQuery's preventDefault() and stopPropagation() functions

A recent discussion with a coworker revealed some contrasting coding practices, mainly concerning his extensive use of the two aforementioned methods in event handlers. Every event handler he creates follows this same pattern... $('span.whatever&apos ...

Eliminate any additional spacing within the pre/code tags

I am currently utilizing prism.js for code highlighting. I have encountered an issue where there are unnecessary white spaces at the top and bottom of my output. You can view a live example here. <pre> <code class="language-css"> &lt ...

Spin the object around the z-axis, with the point serving as the center of rotation

I have a unique challenge with positioning a HUD object on the front of a tube in Three.js. The HUD needs to align itself based on a vector point, always facing towards the high side of that point, regardless of the direction and position of the tube. To b ...

The button event is currently only targeting the initial class. (Jquery)

I am having an issue where only the first instance of the saveBtn class is being saved into local storage when clicked. Can anyone provide some assistance with this? Here is the HTML: <div class="hour-container" id="8am"> & ...

What is the best way to create a Protractor expected condition that verifies the presence of a specific CSS class?

After clicking on the button with the id 'public1', the class goes from ng-pristine to ng-dirty. Here's an example: <input id="public1" class="tile-checkbox ng-valid ng-dirty"> Some Text</input> I am looking for a way to write ...

Looking to transition from Node.js version v4.4.5 to v6.11.0 on your Windows system?

npm cache clean npm update -g I attempted upgrading using the provided commands, but unfortunately, the update did not go through as expected. Seeking advice for a successful update process. (Currently on Node.js 4.4.5 and aiming to upgrade to Node.js 6. ...

Navigating using angular's UI router - Save for later option

I am working on a project that involves a controller and a view. The view consists of three dynamic drop-down menus and a table. When a value is selected in dropdown1, a REST call is triggered to fetch values for dropdown2. The controller contains the nece ...

Setting a cookie in a browser using an AJAX response: A step-by-step guide

When utilizing a Javascript function with jQuery to send a POST request to a web service, the response from the web server includes a header "Set-Cookie: name=value; domain=api.mydomain.com; path=/", along with a JSON body. However, despite this expected ...

Modify the data displayed on the chart by choosing the desired year from the dropdown options

In my Angular app, I am showcasing a chart that visualizes data based on selected starting and ending years from dropdown menus. The X axis represents 18 cities, while the Y axis displays "IAP" values. To calculate the "IAP" values for each city within the ...

Creating an efficient login system for my website - where do I start?

I've recently started diving into the world of web development, starting with HTML, CSS, and a bit of JavaScript. However, I've hit a roadblock - while I can perform basic styling, I'm struggling to make my projects interactive. My main que ...

Accessing the 'window' object within an Angular expression is not permitted unless using a controller

I am attempting to display a <p> only in the context of the HTTP protocol. This is my current progress: angular .module('myApp',[]) .controller('myCtrl', ['$scope', '$window', function($scope, $window){ ...

How can you set a predetermined value for a dropdown menu after populating it with data from a Django database?

I currently have a query in my Views.py file that is used to populate a dropdown menu. The query works properly, but I need it to display a specific value that is stored in a variable based on the user's selection. For example, let's suppose we ...

Modify the transition and design of two progress bars

I'm having an issue with merging two Bootstrap progress bars into one. Initially, the first progress bar appears when the page loads and hides after data is loaded. At the same time, the second progress bar shows up. However, the transition animation ...

Tips for clearing a material-ui search input field with the help of a button

Currently, I am working on a tutorial that involves implementing react material-ui tables along with a search input textfield. I am attempting to enhance this by adding a button that not only resets the table report but also clears the search input textfie ...

Connect the plotly library to interact with the data in a Vue.js application through

I'm currently working on a project that involves using vue.js and the plot.ly JavaScript graph library. I am trying to figure out how to bind "pts" to the data's "TestSentences" in Vue. Below is my code snippet, thanks to everyone who has provide ...

"Is it possible to include a query in a reducer with

Hey, how can I implement this inside a reducer to modify the state's value? doc = { id:"zf123ada123ad", name:"examp", subdoc:{ name:"subdoc examp", subsubdoc:[{ id:"zcgsdf123zaar21", subsubsubdoc:[{ ...

Using react-input-mask together with a child component in React is not compatible

I've been exploring ways to mask a Material UI TextField, and after researching some solutions online, I came across this code snippet: <InputMask mask="(0)999 999 99 99" value={phone} disabled={false} ...

The $save function does not operate properly; although the call is successful, it fails to trigger the .then() method

Attempting to place a call that POSTs an array using $save, but encountering issues with callback function execution. Despite receiving a 200 response, both success and failure callbacks are not triggering. var endpoint = "my valid url"; var ...

exchange the class using only JavaScript

I need help with a code snippet that allows for swapping classes using a loop. The objective is to click on the brown square causing it to move to the position of the blue square, while the blue square moves to the previous position of the brown square. T ...

Display open time slots in increments of 15 minutes on Fullcalendar

Currently, I am utilizing the fullcalendar plugin with the 'agendaweek' view. My goal is to showcase the available time slots as clickable and highlight the busy ones with a red background. Handling the highlighting of busy slots is not an issue ...