Angularjs templateUrl fails to bind attributes inside ng-repeat

假装没事ソ 提交于 2019-11-29 12:23:31

attrs param for templateUrl is not interpolated during directive execution. You may use the following way to achieve this

app.directive("myTemplate", function() {
  return {
    restrict: 'EA',
    replace: false,
    scope: { snippet: '@'},
    template: '<div ng-include="snippet"></div>'
  };
}); 

Demo: http://plnkr.co/edit/2ofO6m45Apmq7kbYWJBG?p=preview

Check out this link

http://plnkr.co/edit/TBmTXztOnYPYxV4qPyjD?p=preview

app.directive("myTemplate", function() {
  return {
    restrict: 'EA',
    replace: true,
    scope: { snippet: '=snippet'},
    link: function(scope, elem, attrs) {
      console.log('We try to load the following snippet:' + scope.snippet);
    },
    template: '<div ng-include="snippet"></div>'
  };
})

You can use ng-include, watching the attrs. Like this:

app.directive("myTemplate", function() {
    return {
        restrict: 'E',
        replace: true,
        link: function(scope, elem, attrs) {
            scope.content = attrs.snippet;
            attrs.$observe("snippet",function(v){
                scope.content = v;
            });
        },
        template: "<div data-ng-include='content'></div>"
    };
});

Just made changes in directive structure. Instead of rendering all templates using ng-repeat we will render it using directive itself, for that we will pass entire template array to directive.

HTML

<div ng-init="snippets = ['snippet1.html','snippet2.html']">
    <my-template snippets="snippets"></my-template>
</div>

Directive

angular.module('myApp', [])
.controller('test',function(){})
    .directive("myTemplate", function ($templateCache, $compile) {
    return {
        restrict: 'EA',
        replace: true,
        scope: {
            snippets: '='
        },
        link: function(scope, element, attrs){
            angular.forEach(scope.snippets, function(val, index){
                //creating new element inside angularjs
                element.append($compile($templateCache.get(val))(scope));
            });
        }
    };
});

Working Fiddle

Hope this could help you. Thanks.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!