Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use $interpolate in AngularJS to reduce automatically generated watchers

Using the ng-repeat directive in AngularJS tends to produce a lot of watchers, as every row contains multiple ng-bind directives to display the row's data, respectively. Per site I have about 2.500 watchers: 100 rows, each row containing seven columns, each containing an ng-bind etc. This sums up to this huge amount of watchers.

I cannot use one-time binding, as the data might change over time (reloaded from backend, not modified by the user). Besides, pagination is not a solution, as the table is grouped in a way that prohibits every pagination approach.

Hence, I'm playing around with the $interpolate function of AngularJS. In particular, I want to extract the html of a single row to a new template, interpolate this row template in my JavaScript code, and add the concatenated rows to my $scope.

Now I have two questions:

  1. Is this a bad approach in general? I still separate markup (a table row is described in a dedicated HTML file) from logic, but maybe there are other drawbacks I overlook at the moment.

  2. How can I load the row template into a variable so I can pass it to the AngularJS functions?

like image 247
strauberry Avatar asked Nov 09 '22 12:11

strauberry


1 Answers

I cannot answer you question 1, but q.2 (load template and use it in JS functions) can be achieved with this:

// add to $templateCache
angular.module("myApp", [])
.run(["$templateCache", function($templateCache) {
    $templateCache.put("myRow.html",
        "<tr><td>my name is: {{name}}</td></tr>");
}]);

//from your directive...
// retrieve from $templateCache and apply to element
var template = $templateCache.get('myRow.html');
var context = { name: "John Smith" };
var result = $interpolate(template)(context);

$element.append(result);
like image 108
ThiagoPXP Avatar answered Nov 14 '22 23:11

ThiagoPXP