Using a $watch on a directive that has an isolated scope to monitor changes in a nested object property retrieved from

I have developed a custom directive with an isolated scope and element. I am utilizing the values passed into the directive to construct d3/dc charts. The data goes through crossfilter on the $scope so that the directive attributes can access it. Despite successfully logging the scope within the directive, I am unable to directly access the nested object without encountering 'undefined' errors.

In the controller:

var data = [{
    "player": "Player A",
        "team": "New York",
        "hits": 200
}, {
    "player": "Player B",
        "team": "New York",
        "hits": 225
}, {
    "player": "Player C",
        "team": "New York",
        "hits": 1
}, {
    "player": "Player D",
        "team": "San Francisco",
        "hits": 268
}, {
    "player": "Player E",
        "team": "San Francisco",
        "hits": 22
}, {
    "player": "Player F",
        "team": "Seattle",
        "hits": 2
}, {
    "player": "Player G",
        "team": "Seattle",
        "hits": 25
}]
$scope.ndx = crossfilter(data);
$scope.playerDim = $scope.ndx.dimension(function (d) {
     return d.player;
});

$scope.playerGrp = $scope.playerDim.group().reduceSum(function (d) {
   return d.hits;
});

HTML:

 <my-chart id="someChart"
                   chart-type="pieChart"
                   height="200"
                   width="200"
                   dimension="playerDim"
                   group="playerGrp" />

Directive:

myApp.directive('myChart', ['chartFactory', function(chartFactory) {
    return {
       restrict: 'E',
       scope: {
          chartType: "@",
          height: "@",
          width: "@",
          dimension: "=",
          group: "="
       },
       link: function(scope, elem, attr) {
          console.log(scope) // correctly displays the dimension object as a property of the object
          console.log(scope.dimension) // returns undefined
       }
    };
}])

It seems like the function hasn't fully set the object when I try to log it, even though it appears there initially. I've attempted using $watch, $timeout, and other methods but have had no luck accessing the nested object.

Could someone please assist me in understanding this issue?

Answer №1

Consider implementing a $watch directive.

link: function(scope, element, attribute) {      
  scope.$watch('dimension', function(newValue, oldValue) {
    if (newValue) {
      console.log('dimension=', scope.dimension);
    }
  });
}

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

Populating inputs dynamically in React.js to receive values

Having recently transitioned to React from React Native, I am faced with a new challenge. I have an array of objects, let's say it contains 5 items. I used the map function to populate views based on the amount of objects, resulting in 5 headings and ...

Suggestions for adding a key-value pair following a specific key within a JSON object with jq?

My JSON file contains a hierarchy structure that looks like this { "hierarchy": { "structure": { "card_11001": [ "addCard_4111" ], "container_11006": [ "mainContainer_11007", ...

The Angular 4 application encountered a TypeError due to being unable to access the 'setupScene' property of an undefined object

How can I execute an Angular class function within the Load function in TypeScript? I am encountering an error when trying to call a method within the load method in Angular CLI, resulting in an undefined function error. import { Component, OnInit ,Elemen ...

Protecting your web applications: JSON wrapped in an Object

As cited in the Owasp CheatSheet Series, under the section 'Protect against JSON Hijacking for Older Browsers', it is recommended to always structure JSON with an object on the outside to prevent exploitation. According to the same source, JSON i ...

What is the best way to send a lengthy JSON string using a GET/POST request on Internet Explorer 8?

Having an issue sending a lengthy JSON string from the front-end to PHP on the back-end. Unfortunately, IE8's 2,048 character limit is causing the request to get cut off, regardless of whether it's a GET or POST request. Any suggestions on how t ...

What is the best approach to sending multiple items in a single request to an API using RESTful principles?

This question delves into the abstract, suggesting that the choice of frameworks used may not have a significant impact. However, the task at hand involves constructing an API using Node & Express and designing the frontend with Angular. Situation: As pa ...

Adding a JSON object or model to your whitestorm.js environment: Step-by-step guide

I have a challenge with loading the object from my json file. const loader = new THREE.ObjectLoader(); loader.load("blue-car.json", function ( car ) { car.position.set(2, 0, 0); car.addTo(world); } ); However, I encountered an error. Here is the err ...

Failed to convert the value "hello" to an ObjectId (string type) for the _id path in the product model

i am currently using node, express, and mongoose with a local mongodb database. all of my routes are functioning correctly except for the last one /hello, which is giving me this error: { "stringValue": "\"hello\"&qu ...

Toggling with Jquery when an image is clicked

I'm trying to wrap my head around the functionality of jquery toggle. My goal is to toggle to the next anchor element with the class plr-anchor when an image with the class go_down is clicked. The information is being populated using maps. Javascript ...

Tips for converting a Java certificate file into a JSON string field

I need to create a JSON file containing all the necessary information for transferring and performing additional operations on another system. One of the fields required is the java certificate. To replicate the contents of the files exactly as they are on ...

Discovering uncategorized elements using javascript

Let's say I have a piece of HTML with some content that is not wrapped in any tags, like this: <html> <body> <p>text in a tag</p> other text outside any tag </body> </html> Is there a way to access the untagged el ...

What is the method for configuring Express to serve static files from a parent directory?

If I have a nodejs express application with the following folder structure: -app - frontend - assets - images - scripts - styles - ... - pages - backend - server.js How can I serve the static files in the assets fold ...

Exploring Twig variables in Node.js with the node-twig package

Despite following the documentation meticulously, and experimenting with various methods, I am still unable to achieve success. I have attempted using the code snippet below, trying to reference the variable in the main file like this: // None of the opti ...

Show divs in identical position when clicking

There are 4 section divs that need to be displayed in the center of the page when clicked, but the last one appears further down. This is likely due to the flex box nature. What is the best way to ensure all sections appear at the exact same location? Ano ...

Displaying the AM/PM indicator in lowercase using AngularJS

Employing AngularJS's date filter to format a time stamp has been quite effective for me. However, I am looking to have the AM/PM indicator (a) displayed in lowercase. This is the expression I am utilizing: {{item.date | date: 'h:mma, dd MMM y& ...

Enhance your service stack by integrating AngularJS with RavenDB using the most effective approach

I have set up a Service Stack AngularJS VS template application. Initially, the project structure includes: • X.AngularJS • X.AngularJS.ServiceInterface • X.AngularJS.ServiceModel • X.AngularJS.Tests In this setup, RavenDb is used as the ...

Error TS2322: Cannot assign type 'Promise<Hero | undefined>' to type 'Promise<Hero>'

I am currently studying angular4 using the angular tutorial. Here is a function to retrieve a hero from a service: @Injectable() export class HeroService { getHeroes(): Promise<Hero[]> { return new Promise(resolve => { // ...

When working on a React/Redux application, how do you decide between explicitly passing down a prop or retrieving it from the global state using mapStateToProps?

As I embark on creating my inaugural React-Redux application, a recurring decision I face is whether to employ <PaginationBox perPage={perPage} /> or opt for <PaginationBox /> and then implement the following logic: function mapStateToProps({p ...

Sending Angular an error message from Express

In my application, users have the ability to add movies to their watchlist. I am working on preventing users from adding a movie that already exists in their watchlist. This is the addMovie function in my Angular controller: $scope.addMovie = function (m ...

Debugging JavaScript in ASP .NET (solving quick breakpoint problems)

There seems to be a mystery about setting breakpoints in my JavaScript code - sometimes it works, other times it doesn't. Despite all efforts, I can't seem to figure out what factors contribute to this inconsistency. While debugging the dynamic p ...