简体   繁体   中英

How to change template from link function in Angular.js

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.

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"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM