2

I've created directive widget (which act like ng-view but name of the template is taken from attribute)

app.directive('widget', function() {
    return {
        restrict: 'EA',
        scope: true,
        templateUrl: function(tElement, tAttrs) {
            var page = tAttrs.name + ".html";
            return window.location.href.replace(/[^\/]+$/, '') + page;
        }
    };
});

it work when I create widget like this:

<widget name="page"/>

It display page.html. But will not work with this code (I know that it will return 404 while typing until I finish, but it's just an example)

<input ng-model="widgetName"/>
<widget name="{{widgetName}}"/>

In order to have this dynamic widget, I need to create template using link function, how can I do this? I only know that I need to create scope using {name: '@name'} to bind it with attribute name and that I can use $http in link function but don't know what do do when I got the page from it.

1 Answer 1

4

If you want to have dynamic templateUrl you can simply use ngInclude, binding it to widgetName. In fact:

<div ng-include="widgetName"></div>

This obviously means that widgetName must contain the whole path. You can then wrap it in a directive so you can also do more complex things, like adding '.html' to the widget name and use $scope.$watch on widgetName to check for changes:

app.directive('widget', function() {
    return {
        restrict: 'EA',
        scope: {
            widgetName : '=name'
        },
        controller: function($scope) {
            $scope.$watch('widgetName', function() {
                $scope.templateUrl = $scope.widgetName + '.html';
            });
        },
        template: '<div ng-include="templateUrl"></div>'
    };
});

and the HTML will be like:

<input ng-model="widgetName"/>
<widget name="widgetName"/>
Sign up to request clarification or add additional context in comments.

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.