Search code examples
javascriptangularjsjsonangularjs-directivecrossfilter

$watch on directive with isolated scope for nested object as property from crossfilter


I have created a directive with isolated scope, element, and am using those values passed in to build d3/dc charts. So I have some data that is put through crossfilter on the $scope, so that the directive attributes can read it. Then I am pulling into the directive and logging scope shows it fine, however I can't access the nested object specifically/directly without getting undefined.

within 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) // shows the dimension object as a property on the object just fine
          console.log(scope.dimension) // undefined
       }
    };
}])

My guess is that the function hasn't really set the object there when I console.log it, though it shows it there (misleading). I have tried $watch, $timeout, etc and nothing seems to allow me to get at that nested object.

Can anyone please help me understand what is happening here?


Solution

  • Try using a $watch

    link: function(scope, elem, attr) {      
      scope.$watch('dimension', function(nVal, oVal) {
        if (nVal) {
          console.log('dimension=', scope.dimension);
        }
      });
    }