miquelarranz miquelarranz - 5 months ago 9
JSON Question

Refreshing a directive after updating the configuration

I am a bit confused about how to "redraw" a directive once one of the values that I pass to it has been updated.

What I have is a directive that draws a chart depending on a configuration (a JSON) that I pass to it as a scope parameter. In the controller of the view that contains the directive I can update this configuration and I want to update the directive when the new configuration is updated by the user.

The configuration JSON looks like:

$scope.configuration = {
widget: {
range: {
maximum: 0,
minimum: -20
}
}
}


And the directive looks like:

<my-chart configuration configuration="configuration"></my-chart>


So when I update the configuration I want the directive to refresh the content (like initialise it again).

Answer

You have to use $scope.$watch, or $scope.$watchCollection(). Here is the link

Your code can be like this

    $scope.$watchCollection('$scope.configuration.widget.range', function reInit(values){
init(values)
});

$watchCollection(obj, listener); Shallow watches the properties of an object and fires whenever any of the properties change (for arrays, this implies watching the array items; for object maps, this implies watching the properties). If a change is detected, the listener callback is fired.