After the view is rendered, the $watch directive attribute in Ionic and AngularJS no longer functions as expected

I am looking to develop an attribute directive for ionItem that will monitor its own value:

<ion-item ng-repeat="item in items" my-dir="{{data.watchedValue}}">….</ion-item>

I am facing challenges in creating the correct watch statement within the directive. The watch function is only triggered once during the initial rendering of the view. Subsequently, it does not respond when data.watchedValue undergoes changes.

An important aspect of this directive is that it is a child of the ionItem directive.

I have experimented with different approaches (refer to the comments in the source code of my-dir), but none of them seem to be effective.

Directive:

.directive('myDir', function() {
  return {
    restrict: 'A',
    require:  '^ionItem',
    link: function(scope, element, attr, itemCtrl) {
      console.log('my-dir initial value: ' + attr.myDir);

      if (angular.isDefined(attr.myDir)) {
        // scope.$watch("(" + attr.myDir + " === \"true\")", function(value) {
        // scope.$watch('!!(' + attr.myDir + ')', function(value) {
        scope.$watch(attr.myDir, function(value) {
          console.log('my-dir watch new value:  ' + value);
        });
      }

    } // link
  }; // return
}) // directive

Simplified usage of the directive:

<button class="button" ng-click="data.watchedValue = !data.watchedValue">
  Change Value
</button>

<ion-content>
  <ion-list>
    <ion-item ng-repeat="item in items" my-dir="{{data.watchedValue}}">
      Item {{ item.id }}. Watched property: {{ data.watchedValue }}
    </ion-item>
  </ion-list>
</ion-content>

Code Pen featuring a complete example. Click on the Change Value button to change the value.

Keep an eye on the console for any logs after the initial display.

Answer №1

When working with directives, it is important to pass scope variables correctly.

<ion-item ng-repeat="item in items" my-dir="data.watchedValue">
  Item {{ item.id }}. Watched property: {{ data.watchedValue }}
</ion-item>

Alternatively,

Another option is to utilize attrs.$observe instead of $scope.$watch, which will monitor the interpolated value specified on the attribute.

If data.watchedValue contains an object, then opting for the first approach is recommended.

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 navigation bar is unresponsive to clicks

I am facing an issue with a bootstrap nav element in which I have included some icons for closing and minimizing. Unfortunately, these icons are not clickable when placed within the nav. However, when I positioned them outside of the nav, they became click ...

Prevent User Input with JavaScript

Having trouble blocking certain keys with my code: { } | ~ Looking for a way to include these keys in the block: <html><head> <script> function blockKeys(){ if ((event.keyCode > 32 && event.keyCode < 48) || (event.keyCode ...

The request is unsuccessful due to the absence of the 'Access-Control-Allow-Origin' header

I've set up a form using Get Response (the email client) and I'm attempting to implement ajax in order to display a custom success or failure message upon submission. The code seems to be functioning correctly. However, as soon as I connect the a ...

Guide to monitoring the modifications made in a DNN text editor within a web form before submitting the page

In my endeavor to develop a JavaScript function that monitors changes made in a web form when the page is submitted, I have encountered an issue. While for regular .NET textbox or textarea fields, I can compare the value with the default value using the fo ...

Refreshing the Span Element using Ajax and php

Hello there, Stack Overflow community! I have a basic PHP script (countsomething.php) that retrieves a number and displays it using echo. How can I use AJAX to automatically update a simple span element on my HTML page? I've attempted to trigger th ...

Is it possible to store data using express.js and display it on a webpage without utilizing a database?

Currently, I am working on a project that involves creating a website where users can input blog text posts and then view those posts. My tech stack includes HTML, CSS, JavaScript, Node.js, EJS, and Express.js. Due to restrictions, I cannot use a database ...

Having trouble loading events on Fullcalendar.io?

Our team is utilizing fullcalendar.io and aiming to retrieve an event from our API controller. The Controller [Route("api/Bookings")] public class BookingApiController { // GET [HttpGet] public string Get() { ...

Create intricate designs by drawing shapes and rotating them in various directions using three.js

Imagine I have a box in Three.js that I want to draw incrementally in various directions. Currently, the line is drawn from left to right by simply incrementing the x value. Is there a way to rotate the rectangle so that it moves in different directions wi ...

How to determine if a ROW already exists in a Database by executing a query in NodeJS

I've been struggling with this issue for quite some time now and I haven't been able to find a solution. After searching on multiple platforms, including Stackoverflow, I have only come across PHP or C# code that partially matches my problem. My ...

Unable to pass parameter in ngRoute

When I pass /?preview=true in my function and catch it in app.js with $route.current.params.preview, it appears to be undefined when outputting to the console log. Can someone please assist me in resolving this error? Below is blah.js which will navigate ...

What could be causing the video not to display in landscape mode on the iPad Pro?

I'm having an issue with a standard HTML5 <video> on my website. The videos are working fine on most devices, however there is a problem specifically with the iPad Pro in landscape orientation. It seems to work properly in portrait orientation ...

Troubleshooting HTTP Response Body Encoding Problem in Node.js

When making HTTP requests with the native 'http' module, unicode characters are not displayed correctly in the response body. Instead of showing the actual value, question mark characters appear. Below is a snippet of the code that I am working w ...

What is the process by which Next.js uses useRouter() to interpret the mapping variable?

const router = useRouter(); return ( <> {Usercategory.map((user,index)=>{ return <div className='user-li' key={index} onClick={()=>{router.push(user.link)}}> <li> {use ...

Submitting form occurs upon selecting autocomplete suggestion

When a user fills out my form and hits the Go button or presses Enter, the form submits. However, when typing in the text box, it triggers an auto-complete feature after just one character. If the user uses arrow keys to navigate through the auto-complete ...

Adjust the size of the mat-expansion indicator to your desired height and width

Trying to modify the width and height of the mat indicator has been a bit challenging. Despite following suggestions from other similar questions, such as adjusting the border width and padding, I am still unable to see the changes reflect in my CSS file ...

What is the best way to enhance an object using a class in ES6?

In an effort to improve the clarity of my ES6 class definition, my current code looks like this: class SomeClass { constructor({a, b, c, d, e}) { this.a = a; this.b = b; this.c = c; this.d = d; this.e = e; // additional code here ...

The term 'MapEditServiceConfig' is being incorrectly utilized as a value in this context, even though it is meant to refer to a type

Why am I receiving an error for MapEditServiceConfig, where it refers to a type? Also, what does MapEditServiceConfig {} represent as an interface, and what is the significance of these brackets? export interface MapEditServiceConfig extends AppCredenti ...

What is the best way to iterate through an array of objects in Angular 2 and retrieve a specific key from each object?

I am working with an array of objects where I need to iterate over the array, access a specific key in each object, and check if the string property matches any words from another array. If there is a match, I want to perform a certain action. While I can ...

Javascript Parameter

Each time I enter scroll(0,10,200,10); into my code, it seems to output the strings "xxpos" or "yypos" instead of the actual values. I attempted to remove the apostrophes around them, but unfortunately, that did not resolve the issue. scroll = function( ...

AngularJS view does not wait for the completion of $http.get request

Within my controller, the code snippet below is present... $scope.products = dataService.getJsonData(); console.log($scope.products); The corresponding code in my dataservice is as follows: .service('dataService', function ($http) { t ...