FED-icons-01 FED-icons-02 FED-icons-03 FED-icons-04 FED-icons-05 FED-icons-06 FED-icons-07 FED-icons-08 FED-icons-09 FED-icons-10 FED-icons-11

A previous blog post I wrote ('How to build a UI without seeing the data'), investigated building dynamic user interfaces. The approach I demonstrated used a directive in which a template was assigned based on a data type. Below is the code snippet from the previous post.

directive('formInputDirective', function() {
    return{
        restrict: 'C',
        template: '<div ng-include="getContentUrl()"></div>',
        scope: {
            directiveData: '='
        },
        controller: function($scope, $filter, clientSettings) {
            $scope.directiveData.type = clientSettings.elementTypes[$scope.directiveData.type];
        },
        link: function(scope, attrs, element){
            scope.getContentUrl = function() {
                return 'partials/fragments/' + scope.directiveData.type + '.html';
            }
        }
    }
});

Here; the template contains an ng-include which returns a value from a function. This does indeed work as expected, however, there may be some performance issues due to this setup. Anytime scope changes, the getContentUrl function will be re-run performing any potential function logic. Any ng attribute calling a function will do the same.

If we change the above directive to:

directive('formInputDirective', function() {
    return{
        restrict: 'C',
        template: '<div ng-include="templateUrl"></div>',
        scope: {
            directiveData: '='
        },
        controller: function($scope, clientSettings) {
            var type = clientSettings.elementTypes[$scope.directiveData.type];
            $scope.templateUrl = 'partials/fragments/' + type + '.html';
        }
    }
});

Now we are assigning the templateUrl to a scope variable instead of a function. If scope is changed, it just has to look to see if this variable has changed instead of running a function which may have to perform logic.

In the end, both approaches accomplish the same result but we have to be cognizant of performance when building large applications. Every little bit helps.


Peter Unsworth

Founder / Application Architect