Search code examples
javascriptangularjsangularjs-ng-include

AngularJS creating a directive to extend ng-include with proper base url


So due to restrictions I have at work I am getting some pretty long includes. To avoid this I have tried creating the following directive:

app.directive('viewInclude', [function() {
        var baseUrl = 'fams360frontend/views/default/glap';
        return {
            scope: {
                viewInclude: '@'
            },
            template: '<div ng-include="link"></div>',
            link: function($scope) {
              $scope.link = baseUrl + $scope.viewInclude;                  
            }
        };
    }]);

I then call it like this:

<view-include src="'/partials/ientry-header.html'"></view-include>      

I am pretty new to Angular so this may be a simple issue but I can't seem to figure out where I am going wrong. I get this error on render:

Error: [$parse:syntax] <!-- ngInclude: fams360frontend/views/default/glap{{viewInclude}} -->

EDIT:

I have updated my code using the answer below but I now no longer get the bank bindings...any ideas?

The included file:

<div style="display: inline-block;">
    <div style="display: inline-block;">
        <span>Bank Account:</span>
    </div>
    <div style="display: inline-block; margin-left: 10px;">
        <span>{{bank.bank_number}} - {{bank.account_name}}</span>
    </div>
</div>
<div style="display: inline-block; margin-left: 75px;">
    <div style="display: inline-block;">
        <span>Company:</span>
    </div>
    <div style="display: inline-block; margin-left: 10px;">
        <span>{{bank.company_number}} - {{bank.company_name}}</span>
    </div>
</div>

Solution

  • Add a link function and concatenate.

    app.directive('viewInclude', [function() {
        var baseUrl = 'fams360frontend/views/default/glap';
        return {
            replace: true,
            scope: {
                viewInclude: '@'
            },
            template: '<div ng-include="link"></div>',
            link: function($scope) {
              $scope.link = baseUrl + $scope.viewInclude;                  
            }
        };
    }]);
    

    Additionally. I believe your html needs to be.

    <div view-include="asdf"></div> <!-- view-include should be an attribute. And since you're using `@` you don't need to wrap the string in single quotes -->