21 May 2015

Motivation

To use ng-repeat to dynamically generate directives according to dataset. Each directive controls the assign dataset element.

Sample Code

The ng-repeat block :

<div ng-repeat="data in objectDataset">
	<slider-ctrl data="data"></slider-ctrl>
</div>

The slider directive js:

app.directive('sliderCtrl', function(){  
	return {  
		link: link,  
		restrict : 'E',  
		scope: {  
			data: '='  
		},  
		templateUrl : 'src/directives/sliderCtrl.html'  
	};  
});

The slider directive html:

<p>Current Value = </p>    
<input type="range" ng-model="data.value">

Notes

  • The wrong practice :
<p>Current Value = </p>    
<input type="range" ng-model="data">

In this example, each iteration will create a childScope, and also assign the value to a new property data. When we change the value, ng-repeat will create new childScope for this new value, not overwriting the old one, and create performance issue.

To correct this issue, we have to pass the reference of the value to ng-model. Remember, “if you are not seeing a “ . “ in ng-model, you are doing something wrong.”



blog comments powered by Disqus