1

I have the three model attributes year, indicator, geography that controls the rendering of a data visualization.

Depending on what is changed in this model, I want to be able to control the rendering of the visualization:

  //Pseudo code
  watch function ( year, indicator, geography ) {
     if(geography.previous == a && geography.current == b){
        renderA()
     }
     if(geography.previous == a && year == 1950){
        renderB()
     }
  }

As the above example demonstrates, I want to be able to compare a previous value to a current and any combination of model changes to determine the rendering.

How would I set this up in Angular?
(possibly including a service for the model and watching multiple attributes ...)

2 Answers 2

1

If you want to watch multiple properties then you can wrap them with object and watch for deep changes on the object

$scope.obj = {
   year : ...
   indicator : ...
   geography : ...
}
$scope.$watch('obj', function(newValue, oldValue) {
   // your logic dependent on changes
}, true);

Note the 3rd true parameter to $watch function. It is responsible for watching for deep changes.

I don't know what you want to render, but if these are completely different templates then you can use ngSwitch.

I am not sure if using some kind of service is a right choice here. I'd lean towards some kind of directive. Mainly because of scope which services don't have. You could just wrap everything with directive and pass your data to directive which does the rendering and logic.

Sign up to request clarification or add additional context in comments.

Comments

0

ng-include can help you here. You can define template for A and B. These template can be server side or client side (using ng-template).

If using client side templates they would look like

<script type="text/ng-template" class="template" id="templateA">
<!-- HTML for A here -->
</script>

<script type="text/ng-template" class="template" id="templateB">
<!-- HTML for B here -->
</script>

You html can not use ng-include to switch template dynamically. The HTML would look like

<div id="renderContainer" ng-include='templateName'></div>

In your controller you can define watch function

//Pseudo code
  watch function ( year, indicator, geography ) {
     if(geography.previous == a && geography.current == b){
        $scope.templateName='templateA';
     }
     if(geography.previous == a && year == 1950){
        $scope.templateName='templateB';
     }
  }

Changing the templateName variable would dynamically change the rendered template in the UI

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.